Scoped thread¶
Category: Units of execution · Status: stub · Lessons: chapter 01, Threads
One line: A thread whose life is bounded by a block: the block cannot be left until the thread has been joined, which is what lets the thread borrow the block's own local variables.
Also called: structured thread, thread::scope.
How it connects¶
flowchart LR
n_dangling_pointer["Dangling pointer"]
n_detached_thread["Detached thread"]
n_task_leak["Leaked tasks"]
n_scoped_thread["Scoped thread"]
n_thread["Thread"]
n_detached_thread ---|vs| n_scoped_thread
n_scoped_thread -->|is a| n_thread
n_scoped_thread -->|prevents| n_dangling_pointer
n_scoped_thread -->|prevents| n_task_leak
classDef center stroke-width:3px
class n_scoped_thread center
classDef outside stroke-dasharray: 4 3
class n_dangling_pointer,n_detached_thread,n_task_leak,n_thread outside
- Is a kind of: Thread
- Helps prevent: Dangling pointer, Leaked tasks
- Often confused with: Detached thread
- See also: Join, Object lifetime, Structured concurrency
In each language¶
| Rust | thread::scope ↗ joins every thread started inside it before returning, so a scoped thread may borrow the caller's locals and needs no 'static bound |
| C++ | std::jthread ↗ joins in its destructor, which bounds the thread by the enclosing block — but nothing checks what the thread captured |
| Java | JEP 505: Structured Concurrency ↗ scopes a set of tasks to a block that does not exit until all of them have finished |
| Python | ThreadPoolExecutor ↗ used as a context manager waits for its threads at the end of the with block |
Where to read more¶
- In this library: Can a thread borrow a local variable?
- Reference: Wikipedia: Structured concurrency ↗