Skip to content

Commit 25dc6a7

Browse files
Rollup merge of rust-lang#41980 - gamazeps:thread-send, r=steveklabnik
[Doc] Add `'static` and `Send` constraints explanations to `thread::spawn` Part of rust-lang#29378. Explains why the constraints on the closure and its return value are `'static` and `Send`. Allows to tick of `thread::spawn` from the list of things to document in the `thread` module. r? @steveklabnik
2 parents 006eca4 + 770bd57 commit 25dc6a7

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/libstd/thread/mod.rs

+22
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,26 @@ impl Builder {
394394
/// want to specify the stack size or the name of the thread, use this API
395395
/// instead.
396396
///
397+
/// As you can see in the signature of `spawn` there are two constraints on
398+
/// both the closure given to `spawn` and its return value, let's explain them:
399+
///
400+
/// - The `'static` constraint means that the closure and its return value
401+
/// must have a lifetime of the whole program execution. The reason for this
402+
/// is that threads can `detach` and outlive the lifetime they have been
403+
/// created in.
404+
/// Indeed if the thread, and by extension its return value, can outlive their
405+
/// caller, we need to make sure that they will be valid afterwards, and since
406+
/// we *can't* know when it will return we need to have them valid as long as
407+
/// possible, that is until the end of the program, hence the `'static`
408+
/// lifetime.
409+
/// - The [`Send`] constraint is because the closure will need to be passed
410+
/// *by value* from the thread where it is spawned to the new thread. Its
411+
/// return value will need to be passed from the new thread to the thread
412+
/// where it is `join`ed.
413+
/// As a reminder, the [`Send`] marker trait, expresses that it is safe to be
414+
/// passed from thread to thread. [`Sync`] expresses that it is safe to have a
415+
/// reference be passed from thread to thread.
416+
///
397417
/// # Panics
398418
///
399419
/// Panics if the OS fails to create a thread; use [`Builder::spawn`]
@@ -460,6 +480,8 @@ impl Builder {
460480
/// [`panic`]: ../../std/macro.panic.html
461481
/// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
462482
/// [`Builder`]: ../../std/thread/struct.Builder.html
483+
/// [`Send`]: ../../std/marker/trait.Send.html
484+
/// [`Sync`]: ../../std/marker/trait.Sync.html
463485
#[stable(feature = "rust1", since = "1.0.0")]
464486
pub fn spawn<F, T>(f: F) -> JoinHandle<T> where
465487
F: FnOnce() -> T, F: Send + 'static, T: Send + 'static

0 commit comments

Comments
 (0)