Skip to content

Commit 770bd57

Browse files
author
Felix Raimundo
committed
Add 'static and Send constraints explanations to thread::spawn
Part of #29378.
1 parent 77f1bec commit 770bd57

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
@@ -367,6 +367,26 @@ impl Builder {
367367
/// want to specify the stack size or the name of the thread, use this API
368368
/// instead.
369369
///
370+
/// As you can see in the signature of `spawn` there are two constraints on
371+
/// both the closure given to `spawn` and its return value, let's explain them:
372+
///
373+
/// - The `'static` constraint means that the closure and its return value
374+
/// must have a lifetime of the whole program execution. The reason for this
375+
/// is that threads can `detach` and outlive the lifetime they have been
376+
/// created in.
377+
/// Indeed if the thread, and by extension its return value, can outlive their
378+
/// caller, we need to make sure that they will be valid afterwards, and since
379+
/// we *can't* know when it will return we need to have them valid as long as
380+
/// possible, that is until the end of the program, hence the `'static`
381+
/// lifetime.
382+
/// - The [`Send`] constraint is because the closure will need to be passed
383+
/// *by value* from the thread where it is spawned to the new thread. Its
384+
/// return value will need to be passed from the new thread to the thread
385+
/// where it is `join`ed.
386+
/// As a reminder, the [`Send`] marker trait, expresses that it is safe to be
387+
/// passed from thread to thread. [`Sync`] expresses that it is safe to have a
388+
/// reference be passed from thread to thread.
389+
///
370390
/// # Panics
371391
///
372392
/// Panics if the OS fails to create a thread; use [`Builder::spawn`]
@@ -433,6 +453,8 @@ impl Builder {
433453
/// [`panic`]: ../../std/macro.panic.html
434454
/// [`Builder::spawn`]: ../../std/thread/struct.Builder.html#method.spawn
435455
/// [`Builder`]: ../../std/thread/struct.Builder.html
456+
/// [`Send`]: ../../std/marker/trait.Send.html
457+
/// [`Sync`]: ../../std/marker/trait.Sync.html
436458
#[stable(feature = "rust1", since = "1.0.0")]
437459
pub fn spawn<F, T>(f: F) -> JoinHandle<T> where
438460
F: FnOnce() -> T, F: Send + 'static, T: Send + 'static

0 commit comments

Comments
 (0)