Skip to content

Commit b76b9e1

Browse files
Felix Raimundogamazeps
Felix Raimundo
authored andcommitted
Expands detach documentation in thread::JoinHande.
Part of #29378 . - Adds an example of a thread detaching. - Expands what `detaching` means.
1 parent 77f1bec commit b76b9e1

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

src/libstd/thread/mod.rs

+28-3
Original file line numberDiff line numberDiff line change
@@ -1019,11 +1019,12 @@ impl<T> JoinInner<T> {
10191019

10201020
/// An owned permission to join on a thread (block on its termination).
10211021
///
1022-
/// A `JoinHandle` *detaches* the child thread when it is dropped.
1022+
/// A `JoinHandle` *detaches* the associated thread when it is dropped, which
1023+
/// means that there is no longer any handle to thread and no way to `join`
1024+
/// on it.
10231025
///
10241026
/// Due to platform restrictions, it is not possible to [`Clone`] this
1025-
/// handle: the ability to join a child thread is a uniquely-owned
1026-
/// permission.
1027+
/// handle: the ability to join a thread is a uniquely-owned permission.
10271028
///
10281029
/// This `struct` is created by the [`thread::spawn`] function and the
10291030
/// [`thread::Builder::spawn`] method.
@@ -1052,6 +1053,30 @@ impl<T> JoinInner<T> {
10521053
/// }).unwrap();
10531054
/// ```
10541055
///
1056+
/// Child being detached and outliving its parent:
1057+
///
1058+
/// ```no_run
1059+
/// use std::thread;
1060+
/// use std::time::Duration;
1061+
///
1062+
/// let original_thread = thread::spawn(|| {
1063+
/// let _detached_thread = thread::spawn(|| {
1064+
/// // Here we sleep to make sure that the first thread returns before.
1065+
/// thread::sleep(Duration::from_millis(10));
1066+
/// // This will be called, even though the JoinHandle is dropped.
1067+
/// println!("♫ Still alive ♫");
1068+
/// });
1069+
/// });
1070+
///
1071+
/// let _ = original_thread.join();
1072+
/// println!("Original thread is joined.");
1073+
///
1074+
/// // We make sure that the new thread has time to run, before the main
1075+
/// // thread returns.
1076+
///
1077+
/// thread::sleep(Duration::from_millis(1000));
1078+
/// ```
1079+
///
10551080
/// [`Clone`]: ../../std/clone/trait.Clone.html
10561081
/// [`thread::spawn`]: fn.spawn.html
10571082
/// [`thread::Builder::spawn`]: struct.Builder.html#method.spawn

0 commit comments

Comments
 (0)