]>
Commit | Line | Data |
---|---|---|
54a0048b | 1 | //! Native threads. |
1a4d82fc JJ |
2 | //! |
3 | //! ## The threading model | |
4 | //! | |
5 | //! An executing Rust program consists of a collection of native OS threads, | |
a7813a04 XL |
6 | //! each with their own stack and local state. Threads can be named, and |
7 | //! provide some built-in support for low-level synchronization. | |
1a4d82fc JJ |
8 | //! |
9 | //! Communication between threads can be done through | |
476ff2be | 10 | //! [channels], Rust's message-passing types, along with [other forms of thread |
1a4d82fc JJ |
11 | //! synchronization](../../std/sync/index.html) and shared-memory data |
12 | //! structures. In particular, types that are guaranteed to be | |
13 | //! threadsafe are easily shared between threads using the | |
476ff2be | 14 | //! atomically-reference-counted container, [`Arc`]. |
1a4d82fc JJ |
15 | //! |
16 | //! Fatal logic errors in Rust cause *thread panic*, during which | |
17 | //! a thread will unwind the stack, running destructors and freeing | |
abe05a73 XL |
18 | //! owned resources. While not meant as a 'try/catch' mechanism, panics |
19 | //! in Rust can nonetheless be caught (unless compiling with `panic=abort`) with | |
20 | //! [`catch_unwind`](../../std/panic/fn.catch_unwind.html) and recovered | |
21 | //! from, or alternatively be resumed with | |
22 | //! [`resume_unwind`](../../std/panic/fn.resume_unwind.html). If the panic | |
23 | //! is not caught the thread will exit, but the panic may optionally be | |
24 | //! detected from a different thread with [`join`]. If the main thread panics | |
25 | //! without the panic being caught, the application will exit with a | |
26 | //! non-zero exit code. | |
1a4d82fc JJ |
27 | //! |
28 | //! When the main thread of a Rust program terminates, the entire program shuts | |
29 | //! down, even if other threads are still running. However, this module provides | |
30 | //! convenient facilities for automatically waiting for the termination of a | |
c34b1796 | 31 | //! child thread (i.e., join). |
1a4d82fc | 32 | //! |
1a4d82fc JJ |
33 | //! ## Spawning a thread |
34 | //! | |
476ff2be | 35 | //! A new thread can be spawned using the [`thread::spawn`][`spawn`] function: |
1a4d82fc JJ |
36 | //! |
37 | //! ```rust | |
85aaf69f | 38 | //! use std::thread; |
1a4d82fc | 39 | //! |
85aaf69f | 40 | //! thread::spawn(move || { |
c34b1796 | 41 | //! // some work here |
1a4d82fc JJ |
42 | //! }); |
43 | //! ``` | |
44 | //! | |
85aaf69f | 45 | //! In this example, the spawned thread is "detached" from the current |
c34b1796 AL |
46 | //! thread. This means that it can outlive its parent (the thread that spawned |
47 | //! it), unless this parent is the main thread. | |
1a4d82fc | 48 | //! |
9346a6ac | 49 | //! The parent thread can also wait on the completion of the child |
476ff2be | 50 | //! thread; a call to [`spawn`] produces a [`JoinHandle`], which provides |
9346a6ac AL |
51 | //! a `join` method for waiting: |
52 | //! | |
53 | //! ```rust | |
54 | //! use std::thread; | |
55 | //! | |
56 | //! let child = thread::spawn(move || { | |
57 | //! // some work here | |
58 | //! }); | |
59 | //! // some work here | |
60 | //! let res = child.join(); | |
61 | //! ``` | |
62 | //! | |
7cac9316 | 63 | //! The [`join`] method returns a [`thread::Result`] containing [`Ok`] of the final |
476ff2be SL |
64 | //! value produced by the child thread, or [`Err`] of the value given to |
65 | //! a call to [`panic!`] if the child panicked. | |
9346a6ac | 66 | //! |
1a4d82fc JJ |
67 | //! ## Configuring threads |
68 | //! | |
476ff2be | 69 | //! A new thread can be configured before it is spawned via the [`Builder`] type, |
bd371182 | 70 | //! which currently allows you to set the name and stack size for the child thread: |
1a4d82fc JJ |
71 | //! |
72 | //! ```rust | |
9346a6ac | 73 | //! # #![allow(unused_must_use)] |
1a4d82fc JJ |
74 | //! use std::thread; |
75 | //! | |
76 | //! thread::Builder::new().name("child1".to_string()).spawn(move || { | |
c34b1796 | 77 | //! println!("Hello, world!"); |
1a4d82fc JJ |
78 | //! }); |
79 | //! ``` | |
80 | //! | |
a7813a04 XL |
81 | //! ## The `Thread` type |
82 | //! | |
476ff2be | 83 | //! Threads are represented via the [`Thread`] type, which you can get in one of |
a7813a04 XL |
84 | //! two ways: |
85 | //! | |
0731742a | 86 | //! * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`] |
cc61c64b XL |
87 | //! function, and calling [`thread`][`JoinHandle::thread`] on the [`JoinHandle`]. |
88 | //! * By requesting the current thread, using the [`thread::current`] function. | |
a7813a04 | 89 | //! |
cc61c64b | 90 | //! The [`thread::current`] function is available even for threads not spawned |
a7813a04 XL |
91 | //! by the APIs of this module. |
92 | //! | |
c34b1796 AL |
93 | //! ## Thread-local storage |
94 | //! | |
9e0c209e SL |
95 | //! This module also provides an implementation of thread-local storage for Rust |
96 | //! programs. Thread-local storage is a method of storing data into a global | |
97 | //! variable that each thread in the program will have its own copy of. | |
c34b1796 AL |
98 | //! Threads do not share this data, so accesses do not need to be synchronized. |
99 | //! | |
9e0c209e SL |
100 | //! A thread-local key owns the value it contains and will destroy the value when the |
101 | //! thread exits. It is created with the [`thread_local!`] macro and can contain any | |
102 | //! value that is `'static` (no borrowed pointers). It provides an accessor function, | |
103 | //! [`with`], that yields a shared reference to the value to the specified | |
104 | //! closure. Thread-local keys allow only shared access to values, as there would be no | |
105 | //! way to guarantee uniqueness if mutable borrows were allowed. Most values | |
c34b1796 | 106 | //! will want to make use of some form of **interior mutability** through the |
9e0c209e SL |
107 | //! [`Cell`] or [`RefCell`] types. |
108 | //! | |
3b2f2976 XL |
109 | //! ## Naming threads |
110 | //! | |
111 | //! Threads are able to have associated names for identification purposes. By default, spawned | |
112 | //! threads are unnamed. To specify a name for a thread, build the thread with [`Builder`] and pass | |
113 | //! the desired thread name to [`Builder::name`]. To retrieve the thread name from within the | |
114 | //! thread, use [`Thread::name`]. A couple examples of where the name of a thread gets used: | |
115 | //! | |
116 | //! * If a panic occurs in a named thread, the thread name will be printed in the panic message. | |
0731742a | 117 | //! * The thread name is provided to the OS where applicable (e.g., `pthread_setname_np` in |
3b2f2976 XL |
118 | //! unix-like platforms). |
119 | //! | |
120 | //! ## Stack size | |
121 | //! | |
122 | //! The default stack size for spawned threads is 2 MiB, though this particular stack size is | |
123 | //! subject to change in the future. There are two ways to manually specify the stack size for | |
124 | //! spawned threads: | |
125 | //! | |
126 | //! * Build the thread with [`Builder`] and pass the desired stack size to [`Builder::stack_size`]. | |
127 | //! * Set the `RUST_MIN_STACK` environment variable to an integer representing the desired stack | |
128 | //! size (in bytes). Note that setting [`Builder::stack_size`] will override this. | |
129 | //! | |
130 | //! Note that the stack size of the main thread is *not* determined by Rust. | |
131 | //! | |
3dfed10e XL |
132 | //! [channels]: crate::sync::mpsc |
133 | //! [`join`]: JoinHandle::join | |
134 | //! [`Result`]: crate::result::Result | |
135 | //! [`Ok`]: crate::result::Result::Ok | |
136 | //! [`Err`]: crate::result::Result::Err | |
137 | //! [`thread::current`]: current | |
138 | //! [`thread::Result`]: Result | |
139 | //! [`unpark`]: Thread::unpark | |
140 | //! [`Thread::name`]: Thread::name | |
141 | //! [`thread::park_timeout`]: park_timeout | |
142 | //! [`Cell`]: crate::cell::Cell | |
143 | //! [`RefCell`]: crate::cell::RefCell | |
144 | //! [`with`]: LocalKey::with | |
1a4d82fc | 145 | |
85aaf69f | 146 | #![stable(feature = "rust1", since = "1.0.0")] |
1b1a35ee XL |
147 | #![deny(unsafe_op_in_unsafe_fn)] |
148 | ||
149 | #[cfg(all(test, not(target_os = "emscripten")))] | |
150 | mod tests; | |
85aaf69f | 151 | |
532ac7d7 | 152 | use crate::any::Any; |
532ac7d7 XL |
153 | use crate::cell::UnsafeCell; |
154 | use crate::ffi::{CStr, CString}; | |
155 | use crate::fmt; | |
156 | use crate::io; | |
157 | use crate::mem; | |
158 | use crate::num::NonZeroU64; | |
159 | use crate::panic; | |
160 | use crate::panicking; | |
161 | use crate::str; | |
1b1a35ee | 162 | use crate::sync::Arc; |
532ac7d7 XL |
163 | use crate::sys::thread as imp; |
164 | use crate::sys_common::mutex; | |
532ac7d7 | 165 | use crate::sys_common::thread; |
dfeec247 | 166 | use crate::sys_common::thread_info; |
1b1a35ee | 167 | use crate::sys_common::thread_parker::Parker; |
532ac7d7 XL |
168 | use crate::sys_common::{AsInner, IntoInner}; |
169 | use crate::time::Duration; | |
1a4d82fc | 170 | |
c34b1796 AL |
171 | //////////////////////////////////////////////////////////////////////////////// |
172 | // Thread-local storage | |
173 | //////////////////////////////////////////////////////////////////////////////// | |
174 | ||
dfeec247 XL |
175 | #[macro_use] |
176 | mod local; | |
9346a6ac AL |
177 | |
178 | #[stable(feature = "rust1", since = "1.0.0")] | |
dfeec247 | 179 | pub use self::local::{AccessError, LocalKey}; |
9346a6ac | 180 | |
c30ab7b3 SL |
181 | // The types used by the thread_local! macro to access TLS keys. Note that there |
182 | // are two types, the "OS" type and the "fast" type. The OS thread local key | |
183 | // type is accessed via platform-specific API calls and is slow, while the fast | |
184 | // key type is accessed via code generated via LLVM, where TLS keys are set up | |
185 | // by the elf linker. Note that the OS TLS type is always available: on macOS | |
186 | // the standard library is compiled with support for older platform versions | |
187 | // where fast TLS was not available; end-user code is compiled with fast TLS | |
188 | // where available, but both are needed. | |
189 | ||
dfeec247 | 190 | #[unstable(feature = "libstd_thread_internals", issue = "none")] |
9cc50fc6 | 191 | #[cfg(target_thread_local)] |
dfeec247 XL |
192 | #[doc(hidden)] |
193 | pub use self::local::fast::Key as __FastLocalKeyInner; | |
194 | #[unstable(feature = "libstd_thread_internals", issue = "none")] | |
195 | #[doc(hidden)] | |
196 | pub use self::local::os::Key as __OsLocalKeyInner; | |
197 | #[unstable(feature = "libstd_thread_internals", issue = "none")] | |
198 | #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))] | |
199 | #[doc(hidden)] | |
200 | pub use self::local::statik::Key as __StaticLocalKeyInner; | |
c34b1796 AL |
201 | |
202 | //////////////////////////////////////////////////////////////////////////////// | |
203 | // Builder | |
204 | //////////////////////////////////////////////////////////////////////////////// | |
1a4d82fc | 205 | |
7cac9316 XL |
206 | /// Thread factory, which can be used in order to configure the properties of |
207 | /// a new thread. | |
208 | /// | |
209 | /// Methods can be chained on it in order to configure it. | |
210 | /// | |
211 | /// The two configurations available are: | |
212 | /// | |
3b2f2976 XL |
213 | /// - [`name`]: specifies an [associated name for the thread][naming-threads] |
214 | /// - [`stack_size`]: specifies the [desired stack size for the thread][stack-size] | |
7cac9316 XL |
215 | /// |
216 | /// The [`spawn`] method will take ownership of the builder and create an | |
217 | /// [`io::Result`] to the thread handle with the given configuration. | |
218 | /// | |
219 | /// The [`thread::spawn`] free function uses a `Builder` with default | |
220 | /// configuration and [`unwrap`]s its return value. | |
221 | /// | |
222 | /// You may want to use [`spawn`] instead of [`thread::spawn`], when you want | |
223 | /// to recover from a failure to launch a thread, indeed the free function will | |
a1dfa0c6 | 224 | /// panic where the `Builder` method will return a [`io::Result`]. |
32a655c1 SL |
225 | /// |
226 | /// # Examples | |
227 | /// | |
228 | /// ``` | |
229 | /// use std::thread; | |
230 | /// | |
231 | /// let builder = thread::Builder::new(); | |
232 | /// | |
233 | /// let handler = builder.spawn(|| { | |
234 | /// // thread code | |
235 | /// }).unwrap(); | |
236 | /// | |
237 | /// handler.join().unwrap(); | |
238 | /// ``` | |
7cac9316 | 239 | /// |
3dfed10e XL |
240 | /// [`stack_size`]: Builder::stack_size |
241 | /// [`name`]: Builder::name | |
242 | /// [`spawn`]: Builder::spawn | |
243 | /// [`thread::spawn`]: spawn | |
244 | /// [`io::Result`]: crate::io::Result | |
245 | /// [`unwrap`]: crate::result::Result::unwrap | |
3b2f2976 XL |
246 | /// [naming-threads]: ./index.html#naming-threads |
247 | /// [stack-size]: ./index.html#stack-size | |
85aaf69f | 248 | #[stable(feature = "rust1", since = "1.0.0")] |
32a655c1 | 249 | #[derive(Debug)] |
1a4d82fc JJ |
250 | pub struct Builder { |
251 | // A name for the thread-to-be, for identification in panic messages | |
252 | name: Option<String>, | |
8bb4bdeb | 253 | // The size of the stack for the spawned thread in bytes |
c34b1796 | 254 | stack_size: Option<usize>, |
1a4d82fc JJ |
255 | } |
256 | ||
257 | impl Builder { | |
9346a6ac | 258 | /// Generates the base configuration for spawning a thread, from which |
1a4d82fc | 259 | /// configuration methods can be chained. |
32a655c1 SL |
260 | /// |
261 | /// # Examples | |
262 | /// | |
263 | /// ``` | |
264 | /// use std::thread; | |
265 | /// | |
266 | /// let builder = thread::Builder::new() | |
267 | /// .name("foo".into()) | |
48663c56 | 268 | /// .stack_size(32 * 1024); |
32a655c1 SL |
269 | /// |
270 | /// let handler = builder.spawn(|| { | |
271 | /// // thread code | |
272 | /// }).unwrap(); | |
273 | /// | |
274 | /// handler.join().unwrap(); | |
275 | /// ``` | |
85aaf69f | 276 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 277 | pub fn new() -> Builder { |
dfeec247 | 278 | Builder { name: None, stack_size: None } |
1a4d82fc JJ |
279 | } |
280 | ||
9346a6ac | 281 | /// Names the thread-to-be. Currently the name is used for identification |
1a4d82fc | 282 | /// only in panic messages. |
3157f602 | 283 | /// |
ea8adc8c XL |
284 | /// The name must not contain null bytes (`\0`). |
285 | /// | |
3b2f2976 XL |
286 | /// For more information about named threads, see |
287 | /// [this module-level documentation][naming-threads]. | |
288 | /// | |
3157f602 XL |
289 | /// # Examples |
290 | /// | |
32a655c1 | 291 | /// ``` |
3157f602 XL |
292 | /// use std::thread; |
293 | /// | |
294 | /// let builder = thread::Builder::new() | |
295 | /// .name("foo".into()); | |
296 | /// | |
297 | /// let handler = builder.spawn(|| { | |
298 | /// assert_eq!(thread::current().name(), Some("foo")) | |
299 | /// }).unwrap(); | |
300 | /// | |
301 | /// handler.join().unwrap(); | |
302 | /// ``` | |
3b2f2976 XL |
303 | /// |
304 | /// [naming-threads]: ./index.html#naming-threads | |
85aaf69f | 305 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
306 | pub fn name(mut self, name: String) -> Builder { |
307 | self.name = Some(name); | |
308 | self | |
309 | } | |
310 | ||
8bb4bdeb XL |
311 | /// Sets the size of the stack (in bytes) for the new thread. |
312 | /// | |
313 | /// The actual stack size may be greater than this value if | |
a1dfa0c6 | 314 | /// the platform specifies a minimal stack size. |
32a655c1 | 315 | /// |
3b2f2976 XL |
316 | /// For more information about the stack size for threads, see |
317 | /// [this module-level documentation][stack-size]. | |
318 | /// | |
32a655c1 SL |
319 | /// # Examples |
320 | /// | |
321 | /// ``` | |
322 | /// use std::thread; | |
323 | /// | |
8bb4bdeb | 324 | /// let builder = thread::Builder::new().stack_size(32 * 1024); |
32a655c1 | 325 | /// ``` |
3b2f2976 XL |
326 | /// |
327 | /// [stack-size]: ./index.html#stack-size | |
85aaf69f | 328 | #[stable(feature = "rust1", since = "1.0.0")] |
c34b1796 | 329 | pub fn stack_size(mut self, size: usize) -> Builder { |
1a4d82fc JJ |
330 | self.stack_size = Some(size); |
331 | self | |
332 | } | |
333 | ||
7cac9316 XL |
334 | /// Spawns a new thread by taking ownership of the `Builder`, and returns an |
335 | /// [`io::Result`] to its [`JoinHandle`]. | |
1a4d82fc | 336 | /// |
7cac9316 | 337 | /// The spawned thread may outlive the caller (unless the caller thread |
85aaf69f | 338 | /// is the main thread; the whole process is terminated when the main |
bd371182 | 339 | /// thread finishes). The join handle can be used to block on |
85aaf69f SL |
340 | /// termination of the child thread, including recovering its panics. |
341 | /// | |
7cac9316 XL |
342 | /// For a more complete documentation see [`thread::spawn`][`spawn`]. |
343 | /// | |
85aaf69f SL |
344 | /// # Errors |
345 | /// | |
32a655c1 SL |
346 | /// Unlike the [`spawn`] free function, this method yields an |
347 | /// [`io::Result`] to capture any failure to create the thread at | |
85aaf69f | 348 | /// the OS level. |
32a655c1 | 349 | /// |
3dfed10e | 350 | /// [`io::Result`]: crate::io::Result |
32a655c1 | 351 | /// |
ea8adc8c XL |
352 | /// # Panics |
353 | /// | |
354 | /// Panics if a thread name was set and it contained null bytes. | |
355 | /// | |
32a655c1 SL |
356 | /// # Examples |
357 | /// | |
358 | /// ``` | |
359 | /// use std::thread; | |
360 | /// | |
361 | /// let builder = thread::Builder::new(); | |
362 | /// | |
363 | /// let handler = builder.spawn(|| { | |
364 | /// // thread code | |
365 | /// }).unwrap(); | |
366 | /// | |
367 | /// handler.join().unwrap(); | |
368 | /// ``` | |
85aaf69f | 369 | #[stable(feature = "rust1", since = "1.0.0")] |
dfeec247 XL |
370 | pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>> |
371 | where | |
372 | F: FnOnce() -> T, | |
373 | F: Send + 'static, | |
374 | T: Send + 'static, | |
a1dfa0c6 XL |
375 | { |
376 | unsafe { self.spawn_unchecked(f) } | |
377 | } | |
378 | ||
379 | /// Spawns a new thread without any lifetime restrictions by taking ownership | |
380 | /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`]. | |
381 | /// | |
382 | /// The spawned thread may outlive the caller (unless the caller thread | |
383 | /// is the main thread; the whole process is terminated when the main | |
384 | /// thread finishes). The join handle can be used to block on | |
385 | /// termination of the child thread, including recovering its panics. | |
386 | /// | |
387 | /// This method is identical to [`thread::Builder::spawn`][`Builder::spawn`], | |
388 | /// except for the relaxed lifetime bounds, which render it unsafe. | |
389 | /// For a more complete documentation see [`thread::spawn`][`spawn`]. | |
390 | /// | |
391 | /// # Errors | |
392 | /// | |
393 | /// Unlike the [`spawn`] free function, this method yields an | |
394 | /// [`io::Result`] to capture any failure to create the thread at | |
395 | /// the OS level. | |
396 | /// | |
397 | /// # Panics | |
398 | /// | |
399 | /// Panics if a thread name was set and it contained null bytes. | |
400 | /// | |
401 | /// # Safety | |
402 | /// | |
403 | /// The caller has to ensure that no references in the supplied thread closure | |
404 | /// or its return type can outlive the spawned thread's lifetime. This can be | |
405 | /// guaranteed in two ways: | |
406 | /// | |
407 | /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced | |
408 | /// data is dropped | |
0731742a | 409 | /// - use only types with `'static` lifetime bounds, i.e., those with no or only |
a1dfa0c6 XL |
410 | /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`] |
411 | /// and [`thread::spawn`][`spawn`] enforce this property statically) | |
412 | /// | |
413 | /// # Examples | |
414 | /// | |
415 | /// ``` | |
416 | /// #![feature(thread_spawn_unchecked)] | |
417 | /// use std::thread; | |
418 | /// | |
419 | /// let builder = thread::Builder::new(); | |
420 | /// | |
421 | /// let x = 1; | |
422 | /// let thread_x = &x; | |
423 | /// | |
424 | /// let handler = unsafe { | |
425 | /// builder.spawn_unchecked(move || { | |
426 | /// println!("x = {}", *thread_x); | |
427 | /// }).unwrap() | |
428 | /// }; | |
429 | /// | |
430 | /// // caller has to ensure `join()` is called, otherwise | |
431 | /// // it is possible to access freed memory if `x` gets | |
432 | /// // dropped before the thread closure is executed! | |
433 | /// handler.join().unwrap(); | |
434 | /// ``` | |
435 | /// | |
3dfed10e | 436 | /// [`io::Result`]: crate::io::Result |
a1dfa0c6 | 437 | #[unstable(feature = "thread_spawn_unchecked", issue = "55132")] |
dfeec247 XL |
438 | pub unsafe fn spawn_unchecked<'a, F, T>(self, f: F) -> io::Result<JoinHandle<T>> |
439 | where | |
440 | F: FnOnce() -> T, | |
441 | F: Send + 'a, | |
442 | T: Send + 'a, | |
85aaf69f | 443 | { |
c34b1796 | 444 | let Builder { name, stack_size } = self; |
1a4d82fc | 445 | |
ea8adc8c | 446 | let stack_size = stack_size.unwrap_or_else(thread::min_stack); |
85aaf69f | 447 | |
1a4d82fc JJ |
448 | let my_thread = Thread::new(name); |
449 | let their_thread = my_thread.clone(); | |
450 | ||
dfeec247 | 451 | let my_packet: Arc<UnsafeCell<Option<Result<T>>>> = Arc::new(UnsafeCell::new(None)); |
d9579d0f | 452 | let their_packet = my_packet.clone(); |
85aaf69f | 453 | |
85aaf69f | 454 | let main = move || { |
54a0048b | 455 | if let Some(name) = their_thread.cname() { |
d9579d0f | 456 | imp::Thread::set_name(name); |
85aaf69f | 457 | } |
a1dfa0c6 | 458 | |
1b1a35ee XL |
459 | // SAFETY: the stack guard passed is the one for the current thread. |
460 | // This means the current thread's stack and the new thread's stack | |
461 | // are properly set and protected from each other. | |
462 | thread_info::set(unsafe { imp::guard::current() }, their_thread); | |
a1dfa0c6 | 463 | let try_result = panic::catch_unwind(panic::AssertUnwindSafe(|| { |
532ac7d7 | 464 | crate::sys_common::backtrace::__rust_begin_short_backtrace(f) |
a1dfa0c6 | 465 | })); |
1b1a35ee XL |
466 | // SAFETY: `their_packet` as been built just above and moved by the |
467 | // closure (it is an Arc<...>) and `my_packet` will be stored in the | |
468 | // same `JoinInner` as this closure meaning the mutation will be | |
469 | // safe (not modify it and affect a value far away). | |
470 | unsafe { *their_packet.get() = Some(try_result) }; | |
1a4d82fc JJ |
471 | }; |
472 | ||
b039eaaf | 473 | Ok(JoinHandle(JoinInner { |
1b1a35ee XL |
474 | // SAFETY: |
475 | // | |
0731742a XL |
476 | // `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed |
477 | // through FFI or otherwise used with low-level threading primitives that have no | |
478 | // notion of or way to enforce lifetimes. | |
479 | // | |
480 | // As mentioned in the `Safety` section of this function's documentation, the caller of | |
481 | // this function needs to guarantee that the passed-in lifetime is sufficiently long | |
482 | // for the lifetime of the thread. | |
483 | // | |
484 | // Similarly, the `sys` implementation must guarantee that no references to the closure | |
485 | // exist after the thread has terminated, which is signaled by `Thread::join` | |
486 | // returning. | |
1b1a35ee XL |
487 | native: unsafe { |
488 | Some(imp::Thread::new( | |
489 | stack_size, | |
490 | mem::transmute::<Box<dyn FnOnce() + 'a>, Box<dyn FnOnce() + 'static>>( | |
491 | Box::new(main), | |
492 | ), | |
493 | )?) | |
494 | }, | |
85aaf69f | 495 | thread: my_thread, |
d9579d0f | 496 | packet: Packet(my_packet), |
b039eaaf | 497 | })) |
1a4d82fc JJ |
498 | } |
499 | } | |
500 | ||
c34b1796 AL |
501 | //////////////////////////////////////////////////////////////////////////////// |
502 | // Free functions | |
503 | //////////////////////////////////////////////////////////////////////////////// | |
504 | ||
32a655c1 | 505 | /// Spawns a new thread, returning a [`JoinHandle`] for it. |
85aaf69f | 506 | /// |
c34b1796 AL |
507 | /// The join handle will implicitly *detach* the child thread upon being |
508 | /// dropped. In this case, the child thread may outlive the parent (unless | |
509 | /// the parent thread is the main thread; the whole process is terminated when | |
32a655c1 | 510 | /// the main thread finishes). Additionally, the join handle provides a [`join`] |
c34b1796 | 511 | /// method that can be used to join the child thread. If the child thread |
32a655c1 | 512 | /// panics, [`join`] will return an [`Err`] containing the argument given to |
3dfed10e | 513 | /// [`panic!`]. |
85aaf69f | 514 | /// |
7cac9316 XL |
515 | /// This will create a thread using default parameters of [`Builder`], if you |
516 | /// want to specify the stack size or the name of the thread, use this API | |
517 | /// instead. | |
518 | /// | |
519 | /// As you can see in the signature of `spawn` there are two constraints on | |
520 | /// both the closure given to `spawn` and its return value, let's explain them: | |
521 | /// | |
522 | /// - The `'static` constraint means that the closure and its return value | |
523 | /// must have a lifetime of the whole program execution. The reason for this | |
524 | /// is that threads can `detach` and outlive the lifetime they have been | |
525 | /// created in. | |
526 | /// Indeed if the thread, and by extension its return value, can outlive their | |
527 | /// caller, we need to make sure that they will be valid afterwards, and since | |
528 | /// we *can't* know when it will return we need to have them valid as long as | |
529 | /// possible, that is until the end of the program, hence the `'static` | |
530 | /// lifetime. | |
531 | /// - The [`Send`] constraint is because the closure will need to be passed | |
532 | /// *by value* from the thread where it is spawned to the new thread. Its | |
533 | /// return value will need to be passed from the new thread to the thread | |
534 | /// where it is `join`ed. | |
3b2f2976 | 535 | /// As a reminder, the [`Send`] marker trait expresses that it is safe to be |
7cac9316 XL |
536 | /// passed from thread to thread. [`Sync`] expresses that it is safe to have a |
537 | /// reference be passed from thread to thread. | |
538 | /// | |
85aaf69f SL |
539 | /// # Panics |
540 | /// | |
32a655c1 | 541 | /// Panics if the OS fails to create a thread; use [`Builder::spawn`] |
85aaf69f | 542 | /// to recover from such errors. |
32a655c1 | 543 | /// |
32a655c1 SL |
544 | /// # Examples |
545 | /// | |
7cac9316 XL |
546 | /// Creating a thread. |
547 | /// | |
32a655c1 SL |
548 | /// ``` |
549 | /// use std::thread; | |
550 | /// | |
551 | /// let handler = thread::spawn(|| { | |
552 | /// // thread code | |
553 | /// }); | |
554 | /// | |
555 | /// handler.join().unwrap(); | |
556 | /// ``` | |
7cac9316 XL |
557 | /// |
558 | /// As mentioned in the module documentation, threads are usually made to | |
559 | /// communicate using [`channels`], here is how it usually looks. | |
560 | /// | |
561 | /// This example also shows how to use `move`, in order to give ownership | |
562 | /// of values to a thread. | |
563 | /// | |
564 | /// ``` | |
565 | /// use std::thread; | |
566 | /// use std::sync::mpsc::channel; | |
567 | /// | |
568 | /// let (tx, rx) = channel(); | |
569 | /// | |
570 | /// let sender = thread::spawn(move || { | |
abe05a73 XL |
571 | /// tx.send("Hello, thread".to_owned()) |
572 | /// .expect("Unable to send on channel"); | |
7cac9316 XL |
573 | /// }); |
574 | /// | |
575 | /// let receiver = thread::spawn(move || { | |
abe05a73 XL |
576 | /// let value = rx.recv().expect("Unable to receive from channel"); |
577 | /// println!("{}", value); | |
7cac9316 XL |
578 | /// }); |
579 | /// | |
abe05a73 XL |
580 | /// sender.join().expect("The sender thread has panicked"); |
581 | /// receiver.join().expect("The receiver thread has panicked"); | |
7cac9316 XL |
582 | /// ``` |
583 | /// | |
584 | /// A thread can also return a value through its [`JoinHandle`], you can use | |
585 | /// this to make asynchronous computations (futures might be more appropriate | |
586 | /// though). | |
587 | /// | |
588 | /// ``` | |
589 | /// use std::thread; | |
590 | /// | |
591 | /// let computation = thread::spawn(|| { | |
592 | /// // Some expensive computation. | |
593 | /// 42 | |
594 | /// }); | |
595 | /// | |
596 | /// let result = computation.join().unwrap(); | |
597 | /// println!("{}", result); | |
598 | /// ``` | |
599 | /// | |
3dfed10e XL |
600 | /// [`channels`]: crate::sync::mpsc |
601 | /// [`join`]: JoinHandle::join | |
602 | /// [`Err`]: crate::result::Result::Err | |
85aaf69f | 603 | #[stable(feature = "rust1", since = "1.0.0")] |
dfeec247 XL |
604 | pub fn spawn<F, T>(f: F) -> JoinHandle<T> |
605 | where | |
606 | F: FnOnce() -> T, | |
607 | F: Send + 'static, | |
608 | T: Send + 'static, | |
9346a6ac | 609 | { |
9fa01778 | 610 | Builder::new().spawn(f).expect("failed to spawn thread") |
85aaf69f SL |
611 | } |
612 | ||
85aaf69f | 613 | /// Gets a handle to the thread that invokes it. |
9e0c209e | 614 | /// |
32a655c1 | 615 | /// # Examples |
9e0c209e SL |
616 | /// |
617 | /// Getting a handle to the current thread with `thread::current()`: | |
618 | /// | |
619 | /// ``` | |
620 | /// use std::thread; | |
621 | /// | |
622 | /// let handler = thread::Builder::new() | |
623 | /// .name("named thread".into()) | |
624 | /// .spawn(|| { | |
625 | /// let handle = thread::current(); | |
626 | /// assert_eq!(handle.name(), Some("named thread")); | |
627 | /// }) | |
628 | /// .unwrap(); | |
629 | /// | |
630 | /// handler.join().unwrap(); | |
631 | /// ``` | |
85aaf69f SL |
632 | #[stable(feature = "rust1", since = "1.0.0")] |
633 | pub fn current() -> Thread { | |
dfeec247 | 634 | thread_info::current_thread().expect( |
3dfed10e XL |
635 | "use of std::thread::current() is not possible \ |
636 | after the thread's local data has been destroyed", | |
dfeec247 | 637 | ) |
85aaf69f SL |
638 | } |
639 | ||
9346a6ac | 640 | /// Cooperatively gives up a timeslice to the OS scheduler. |
32a655c1 | 641 | /// |
7cac9316 XL |
642 | /// This is used when the programmer knows that the thread will have nothing |
643 | /// to do for some time, and thus avoid wasting computing time. | |
644 | /// | |
645 | /// For example when polling on a resource, it is common to check that it is | |
646 | /// available, and if not to yield in order to avoid busy waiting. | |
647 | /// | |
648 | /// Thus the pattern of `yield`ing after a failed poll is rather common when | |
649 | /// implementing low-level shared resources or synchronization primitives. | |
650 | /// | |
0bf4aa26 | 651 | /// However programmers will usually prefer to use [`channel`]s, [`Condvar`]s, |
3b2f2976 XL |
652 | /// [`Mutex`]es or [`join`] for their synchronization routines, as they avoid |
653 | /// thinking about thread scheduling. | |
7cac9316 XL |
654 | /// |
655 | /// Note that [`channel`]s for example are implemented using this primitive. | |
656 | /// Indeed when you call `send` or `recv`, which are blocking, they will yield | |
657 | /// if the channel is not available. | |
658 | /// | |
32a655c1 SL |
659 | /// # Examples |
660 | /// | |
661 | /// ``` | |
662 | /// use std::thread; | |
663 | /// | |
664 | /// thread::yield_now(); | |
665 | /// ``` | |
7cac9316 | 666 | /// |
3dfed10e XL |
667 | /// [`channel`]: crate::sync::mpsc |
668 | /// [`join`]: JoinHandle::join | |
1b1a35ee XL |
669 | /// [`Condvar`]: crate::sync::Condvar |
670 | /// [`Mutex`]: crate::sync::Mutex | |
85aaf69f SL |
671 | #[stable(feature = "rust1", since = "1.0.0")] |
672 | pub fn yield_now() { | |
d9579d0f | 673 | imp::Thread::yield_now() |
85aaf69f SL |
674 | } |
675 | ||
676 | /// Determines whether the current thread is unwinding because of panic. | |
3157f602 | 677 | /// |
7cac9316 XL |
678 | /// A common use of this feature is to poison shared resources when writing |
679 | /// unsafe code, by checking `panicking` when the `drop` is called. | |
680 | /// | |
681 | /// This is usually not needed when writing safe code, as [`Mutex`es][Mutex] | |
682 | /// already poison themselves when a thread panics while holding the lock. | |
683 | /// | |
684 | /// This can also be used in multithreaded applications, in order to send a | |
0731742a | 685 | /// message to other threads warning that a thread has panicked (e.g., for |
7cac9316 XL |
686 | /// monitoring purposes). |
687 | /// | |
3157f602 XL |
688 | /// # Examples |
689 | /// | |
32a655c1 | 690 | /// ```should_panic |
3157f602 XL |
691 | /// use std::thread; |
692 | /// | |
693 | /// struct SomeStruct; | |
694 | /// | |
695 | /// impl Drop for SomeStruct { | |
696 | /// fn drop(&mut self) { | |
697 | /// if thread::panicking() { | |
698 | /// println!("dropped while unwinding"); | |
699 | /// } else { | |
700 | /// println!("dropped while not unwinding"); | |
701 | /// } | |
702 | /// } | |
703 | /// } | |
704 | /// | |
705 | /// { | |
706 | /// print!("a: "); | |
707 | /// let a = SomeStruct; | |
708 | /// } | |
709 | /// | |
710 | /// { | |
711 | /// print!("b: "); | |
712 | /// let b = SomeStruct; | |
713 | /// panic!() | |
714 | /// } | |
715 | /// ``` | |
1b1a35ee XL |
716 | /// |
717 | /// [Mutex]: crate::sync::Mutex | |
85aaf69f SL |
718 | #[inline] |
719 | #[stable(feature = "rust1", since = "1.0.0")] | |
720 | pub fn panicking() -> bool { | |
a7813a04 | 721 | panicking::panicking() |
85aaf69f SL |
722 | } |
723 | ||
0bf4aa26 | 724 | /// Puts the current thread to sleep for at least the specified amount of time. |
c34b1796 AL |
725 | /// |
726 | /// The thread may sleep longer than the duration specified due to scheduling | |
0bf4aa26 | 727 | /// specifics or platform-dependent functionality. It will never sleep less. |
32a655c1 | 728 | /// |
f9f354fc XL |
729 | /// This function is blocking, and should not be used in `async` functions. |
730 | /// | |
0531ce1d | 731 | /// # Platform-specific behavior |
32a655c1 | 732 | /// |
0bf4aa26 XL |
733 | /// On Unix platforms, the underlying syscall may be interrupted by a |
734 | /// spurious wakeup or signal handler. To ensure the sleep occurs for at least | |
735 | /// the specified duration, this function may invoke that system call multiple | |
736 | /// times. | |
32a655c1 SL |
737 | /// |
738 | /// # Examples | |
739 | /// | |
740 | /// ```no_run | |
741 | /// use std::thread; | |
742 | /// | |
743 | /// // Let's sleep for 2 seconds: | |
744 | /// thread::sleep_ms(2000); | |
745 | /// ``` | |
c34b1796 | 746 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 747 | #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::sleep`")] |
c34b1796 | 748 | pub fn sleep_ms(ms: u32) { |
d9579d0f AL |
749 | sleep(Duration::from_millis(ms as u64)) |
750 | } | |
751 | ||
0bf4aa26 | 752 | /// Puts the current thread to sleep for at least the specified amount of time. |
d9579d0f AL |
753 | /// |
754 | /// The thread may sleep longer than the duration specified due to scheduling | |
0bf4aa26 | 755 | /// specifics or platform-dependent functionality. It will never sleep less. |
d9579d0f | 756 | /// |
f9f354fc XL |
757 | /// This function is blocking, and should not be used in `async` functions. |
758 | /// | |
0531ce1d | 759 | /// # Platform-specific behavior |
d9579d0f | 760 | /// |
0bf4aa26 XL |
761 | /// On Unix platforms, the underlying syscall may be interrupted by a |
762 | /// spurious wakeup or signal handler. To ensure the sleep occurs for at least | |
763 | /// the specified duration, this function may invoke that system call multiple | |
764 | /// times. | |
765 | /// Platforms which do not support nanosecond precision for sleeping will | |
766 | /// have `dur` rounded up to the nearest granularity of time they can sleep for. | |
3157f602 XL |
767 | /// |
768 | /// # Examples | |
769 | /// | |
32a655c1 | 770 | /// ```no_run |
3157f602 XL |
771 | /// use std::{thread, time}; |
772 | /// | |
773 | /// let ten_millis = time::Duration::from_millis(10); | |
774 | /// let now = time::Instant::now(); | |
775 | /// | |
776 | /// thread::sleep(ten_millis); | |
777 | /// | |
778 | /// assert!(now.elapsed() >= ten_millis); | |
779 | /// ``` | |
e9174d1e | 780 | #[stable(feature = "thread_sleep", since = "1.4.0")] |
d9579d0f AL |
781 | pub fn sleep(dur: Duration) { |
782 | imp::Thread::sleep(dur) | |
c34b1796 AL |
783 | } |
784 | ||
c1a9b12d SL |
785 | /// Blocks unless or until the current thread's token is made available. |
786 | /// | |
7cac9316 XL |
787 | /// A call to `park` does not guarantee that the thread will remain parked |
788 | /// forever, and callers should be prepared for this possibility. | |
789 | /// | |
790 | /// # park and unpark | |
791 | /// | |
792 | /// Every thread is equipped with some basic low-level blocking support, via the | |
793 | /// [`thread::park`][`park`] function and [`thread::Thread::unpark`][`unpark`] | |
794 | /// method. [`park`] blocks the current thread, which can then be resumed from | |
795 | /// another thread by calling the [`unpark`] method on the blocked thread's | |
796 | /// handle. | |
797 | /// | |
798 | /// Conceptually, each [`Thread`] handle has an associated token, which is | |
799 | /// initially not present: | |
c1a9b12d | 800 | /// |
7cac9316 XL |
801 | /// * The [`thread::park`][`park`] function blocks the current thread unless or |
802 | /// until the token is available for its thread handle, at which point it | |
803 | /// atomically consumes the token. It may also return *spuriously*, without | |
804 | /// consuming the token. [`thread::park_timeout`] does the same, but allows | |
805 | /// specifying a maximum time to block the thread for. | |
806 | /// | |
807 | /// * The [`unpark`] method on a [`Thread`] atomically makes the token available | |
b7449926 XL |
808 | /// if it wasn't already. Because the token is initially absent, [`unpark`] |
809 | /// followed by [`park`] will result in the second call returning immediately. | |
7cac9316 XL |
810 | /// |
811 | /// In other words, each [`Thread`] acts a bit like a spinlock that can be | |
812 | /// locked and unlocked using `park` and `unpark`. | |
c1a9b12d | 813 | /// |
0731742a XL |
814 | /// Notice that being unblocked does not imply any synchronization with someone |
815 | /// that unparked this thread, it could also be spurious. | |
816 | /// For example, it would be a valid, but inefficient, implementation to make both [`park`] and | |
817 | /// [`unpark`] return immediately without doing anything. | |
818 | /// | |
c1a9b12d SL |
819 | /// The API is typically used by acquiring a handle to the current thread, |
820 | /// placing that handle in a shared data structure so that other threads can | |
0731742a | 821 | /// find it, and then `park`ing in a loop. When some desired condition is met, another |
7cac9316 | 822 | /// thread calls [`unpark`] on the handle. |
c1a9b12d | 823 | /// |
7cac9316 | 824 | /// The motivation for this design is twofold: |
c1a9b12d | 825 | /// |
7cac9316 XL |
826 | /// * It avoids the need to allocate mutexes and condvars when building new |
827 | /// synchronization primitives; the threads already provide basic | |
828 | /// blocking/signaling. | |
85aaf69f | 829 | /// |
7cac9316 XL |
830 | /// * It can be implemented very efficiently on many platforms. |
831 | /// | |
832 | /// # Examples | |
833 | /// | |
834 | /// ``` | |
835 | /// use std::thread; | |
0731742a | 836 | /// use std::sync::{Arc, atomic::{Ordering, AtomicBool}}; |
7cac9316 XL |
837 | /// use std::time::Duration; |
838 | /// | |
0731742a XL |
839 | /// let flag = Arc::new(AtomicBool::new(false)); |
840 | /// let flag2 = Arc::clone(&flag); | |
841 | /// | |
842 | /// let parked_thread = thread::spawn(move || { | |
9fa01778 | 843 | /// // We want to wait until the flag is set. We *could* just spin, but using |
0731742a XL |
844 | /// // park/unpark is more efficient. |
845 | /// while !flag2.load(Ordering::Acquire) { | |
7cac9316 XL |
846 | /// println!("Parking thread"); |
847 | /// thread::park(); | |
0731742a XL |
848 | /// // We *could* get here spuriously, i.e., way before the 10ms below are over! |
849 | /// // But that is no problem, we are in a loop until the flag is set anyway. | |
7cac9316 | 850 | /// println!("Thread unparked"); |
0731742a XL |
851 | /// } |
852 | /// println!("Flag received"); | |
853 | /// }); | |
7cac9316 XL |
854 | /// |
855 | /// // Let some time pass for the thread to be spawned. | |
856 | /// thread::sleep(Duration::from_millis(10)); | |
857 | /// | |
0731742a | 858 | /// // Set the flag, and let the thread wake up. |
b7449926 XL |
859 | /// // There is no race condition here, if `unpark` |
860 | /// // happens first, `park` will return immediately. | |
0731742a XL |
861 | /// // Hence there is no risk of a deadlock. |
862 | /// flag.store(true, Ordering::Release); | |
7cac9316 XL |
863 | /// println!("Unpark the thread"); |
864 | /// parked_thread.thread().unpark(); | |
865 | /// | |
866 | /// parked_thread.join().unwrap(); | |
867 | /// ``` | |
868 | /// | |
3dfed10e XL |
869 | /// [`unpark`]: Thread::unpark |
870 | /// [`thread::park_timeout`]: park_timeout | |
85aaf69f SL |
871 | #[stable(feature = "rust1", since = "1.0.0")] |
872 | pub fn park() { | |
1b1a35ee XL |
873 | // SAFETY: park_timeout is called on the parker owned by this thread. |
874 | unsafe { | |
875 | current().inner.parker.park(); | |
85aaf69f | 876 | } |
85aaf69f SL |
877 | } |
878 | ||
7cac9316 | 879 | /// Use [`park_timeout`]. |
5bcae85e | 880 | /// |
9346a6ac | 881 | /// Blocks unless or until the current thread's token is made available or |
85aaf69f SL |
882 | /// the specified duration has been reached (may wake spuriously). |
883 | /// | |
7cac9316 XL |
884 | /// The semantics of this function are equivalent to [`park`] except |
885 | /// that the thread will be blocked for roughly no longer than `dur`. This | |
886 | /// method should not be used for precise timing due to anomalies such as | |
85aaf69f | 887 | /// preemption or platform differences that may not cause the maximum |
3157f602 | 888 | /// amount of time waited to be precisely `ms` long. |
85aaf69f | 889 | /// |
7cac9316 | 890 | /// See the [park documentation][`park`] for more detail. |
c34b1796 | 891 | #[stable(feature = "rust1", since = "1.0.0")] |
92a42be0 | 892 | #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::thread::park_timeout`")] |
c34b1796 | 893 | pub fn park_timeout_ms(ms: u32) { |
d9579d0f AL |
894 | park_timeout(Duration::from_millis(ms as u64)) |
895 | } | |
896 | ||
897 | /// Blocks unless or until the current thread's token is made available or | |
898 | /// the specified duration has been reached (may wake spuriously). | |
899 | /// | |
7cac9316 XL |
900 | /// The semantics of this function are equivalent to [`park`][park] except |
901 | /// that the thread will be blocked for roughly no longer than `dur`. This | |
902 | /// method should not be used for precise timing due to anomalies such as | |
d9579d0f | 903 | /// preemption or platform differences that may not cause the maximum |
3157f602 | 904 | /// amount of time waited to be precisely `dur` long. |
d9579d0f | 905 | /// |
3b2f2976 | 906 | /// See the [park documentation][park] for more details. |
d9579d0f | 907 | /// |
0531ce1d | 908 | /// # Platform-specific behavior |
d9579d0f AL |
909 | /// |
910 | /// Platforms which do not support nanosecond precision for sleeping will have | |
911 | /// `dur` rounded up to the nearest granularity of time they can sleep for. | |
5bcae85e | 912 | /// |
3b2f2976 | 913 | /// # Examples |
5bcae85e SL |
914 | /// |
915 | /// Waiting for the complete expiration of the timeout: | |
916 | /// | |
917 | /// ```rust,no_run | |
918 | /// use std::thread::park_timeout; | |
919 | /// use std::time::{Instant, Duration}; | |
920 | /// | |
921 | /// let timeout = Duration::from_secs(2); | |
922 | /// let beginning_park = Instant::now(); | |
5bcae85e | 923 | /// |
041b39d2 XL |
924 | /// let mut timeout_remaining = timeout; |
925 | /// loop { | |
926 | /// park_timeout(timeout_remaining); | |
927 | /// let elapsed = beginning_park.elapsed(); | |
928 | /// if elapsed >= timeout { | |
929 | /// break; | |
930 | /// } | |
931 | /// println!("restarting park_timeout after {:?}", elapsed); | |
932 | /// timeout_remaining = timeout - elapsed; | |
5bcae85e SL |
933 | /// } |
934 | /// ``` | |
e9174d1e | 935 | #[stable(feature = "park_timeout", since = "1.4.0")] |
d9579d0f | 936 | pub fn park_timeout(dur: Duration) { |
1b1a35ee XL |
937 | // SAFETY: park_timeout is called on the parker owned by this thread. |
938 | unsafe { | |
939 | current().inner.parker.park_timeout(dur); | |
85aaf69f | 940 | } |
85aaf69f SL |
941 | } |
942 | ||
c30ab7b3 SL |
943 | //////////////////////////////////////////////////////////////////////////////// |
944 | // ThreadId | |
945 | //////////////////////////////////////////////////////////////////////////////// | |
946 | ||
947 | /// A unique identifier for a running thread. | |
948 | /// | |
949 | /// A `ThreadId` is an opaque object that has a unique value for each thread | |
cc61c64b | 950 | /// that creates one. `ThreadId`s are not guaranteed to correspond to a thread's |
3b2f2976 XL |
951 | /// system-designated identifier. A `ThreadId` can be retrieved from the [`id`] |
952 | /// method on a [`Thread`]. | |
32a655c1 SL |
953 | /// |
954 | /// # Examples | |
955 | /// | |
956 | /// ``` | |
32a655c1 SL |
957 | /// use std::thread; |
958 | /// | |
cc61c64b XL |
959 | /// let other_thread = thread::spawn(|| { |
960 | /// thread::current().id() | |
961 | /// }); | |
32a655c1 | 962 | /// |
cc61c64b XL |
963 | /// let other_thread_id = other_thread.join().unwrap(); |
964 | /// assert!(thread::current().id() != other_thread_id); | |
32a655c1 | 965 | /// ``` |
3b2f2976 | 966 | /// |
3dfed10e | 967 | /// [`id`]: Thread::id |
7cac9316 | 968 | #[stable(feature = "thread_id", since = "1.19.0")] |
cc61c64b | 969 | #[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)] |
532ac7d7 | 970 | pub struct ThreadId(NonZeroU64); |
c30ab7b3 SL |
971 | |
972 | impl ThreadId { | |
973 | // Generate a new unique thread ID. | |
974 | fn new() -> ThreadId { | |
1b1a35ee XL |
975 | // It is UB to attempt to acquire this mutex reentrantly! |
976 | static GUARD: mutex::StaticMutex = mutex::StaticMutex::new(); | |
532ac7d7 | 977 | static mut COUNTER: u64 = 1; |
c30ab7b3 SL |
978 | |
979 | unsafe { | |
94b46f34 | 980 | let _guard = GUARD.lock(); |
c30ab7b3 SL |
981 | |
982 | // If we somehow use up all our bits, panic so that we're not | |
983 | // covering up subtle bugs of IDs being reused. | |
f9f354fc | 984 | if COUNTER == u64::MAX { |
c30ab7b3 SL |
985 | panic!("failed to generate unique thread ID: bitspace exhausted"); |
986 | } | |
987 | ||
988 | let id = COUNTER; | |
989 | COUNTER += 1; | |
990 | ||
532ac7d7 | 991 | ThreadId(NonZeroU64::new(id).unwrap()) |
c30ab7b3 SL |
992 | } |
993 | } | |
dfeec247 XL |
994 | |
995 | /// This returns a numeric identifier for the thread identified by this | |
996 | /// `ThreadId`. | |
997 | /// | |
998 | /// As noted in the documentation for the type itself, it is essentially an | |
999 | /// opaque ID, but is guaranteed to be unique for each thread. The returned | |
1000 | /// value is entirely opaque -- only equality testing is stable. Note that | |
1001 | /// it is not guaranteed which values new threads will return, and this may | |
1002 | /// change across Rust versions. | |
1003 | #[unstable(feature = "thread_id_value", issue = "67939")] | |
ba9703b0 XL |
1004 | pub fn as_u64(&self) -> NonZeroU64 { |
1005 | self.0 | |
dfeec247 | 1006 | } |
c30ab7b3 SL |
1007 | } |
1008 | ||
c34b1796 AL |
1009 | //////////////////////////////////////////////////////////////////////////////// |
1010 | // Thread | |
1011 | //////////////////////////////////////////////////////////////////////////////// | |
1012 | ||
85aaf69f | 1013 | /// The internal representation of a `Thread` handle |
1a4d82fc | 1014 | struct Inner { |
dfeec247 | 1015 | name: Option<CString>, // Guaranteed to be UTF-8 |
c30ab7b3 | 1016 | id: ThreadId, |
1b1a35ee | 1017 | parker: Parker, |
1a4d82fc JJ |
1018 | } |
1019 | ||
1a4d82fc | 1020 | #[derive(Clone)] |
85aaf69f | 1021 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1022 | /// A handle to a thread. |
32a655c1 | 1023 | /// |
7cac9316 XL |
1024 | /// Threads are represented via the `Thread` type, which you can get in one of |
1025 | /// two ways: | |
32a655c1 | 1026 | /// |
0731742a | 1027 | /// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`] |
7cac9316 XL |
1028 | /// function, and calling [`thread`][`JoinHandle::thread`] on the |
1029 | /// [`JoinHandle`]. | |
1030 | /// * By requesting the current thread, using the [`thread::current`] function. | |
32a655c1 | 1031 | /// |
7cac9316 XL |
1032 | /// The [`thread::current`] function is available even for threads not spawned |
1033 | /// by the APIs of this module. | |
32a655c1 | 1034 | /// |
3b2f2976 | 1035 | /// There is usually no need to create a `Thread` struct yourself, one |
7cac9316 XL |
1036 | /// should instead use a function like `spawn` to create new threads, see the |
1037 | /// docs of [`Builder`] and [`spawn`] for more details. | |
1038 | /// | |
3dfed10e | 1039 | /// [`thread::current`]: current |
1a4d82fc JJ |
1040 | pub struct Thread { |
1041 | inner: Arc<Inner>, | |
1042 | } | |
1043 | ||
1044 | impl Thread { | |
1045 | // Used only internally to construct a thread object without spawning | |
ea8adc8c | 1046 | // Panics if the name contains nuls. |
cc61c64b | 1047 | pub(crate) fn new(name: Option<String>) -> Thread { |
dfeec247 XL |
1048 | let cname = |
1049 | name.map(|n| CString::new(n).expect("thread name may not contain interior null bytes")); | |
1a4d82fc | 1050 | Thread { |
1b1a35ee | 1051 | inner: Arc::new(Inner { name: cname, id: ThreadId::new(), parker: Parker::new() }), |
1a4d82fc JJ |
1052 | } |
1053 | } | |
1054 | ||
1a4d82fc JJ |
1055 | /// Atomically makes the handle's token available if it is not already. |
1056 | /// | |
7cac9316 XL |
1057 | /// Every thread is equipped with some basic low-level blocking support, via |
1058 | /// the [`park`][park] function and the `unpark()` method. These can be | |
1059 | /// used as a more CPU-efficient implementation of a spinlock. | |
1060 | /// | |
1061 | /// See the [park documentation][park] for more details. | |
32a655c1 SL |
1062 | /// |
1063 | /// # Examples | |
1064 | /// | |
1065 | /// ``` | |
1066 | /// use std::thread; | |
7cac9316 | 1067 | /// use std::time::Duration; |
32a655c1 | 1068 | /// |
7cac9316 | 1069 | /// let parked_thread = thread::Builder::new() |
32a655c1 | 1070 | /// .spawn(|| { |
7cac9316 XL |
1071 | /// println!("Parking thread"); |
1072 | /// thread::park(); | |
1073 | /// println!("Thread unparked"); | |
32a655c1 SL |
1074 | /// }) |
1075 | /// .unwrap(); | |
1076 | /// | |
7cac9316 XL |
1077 | /// // Let some time pass for the thread to be spawned. |
1078 | /// thread::sleep(Duration::from_millis(10)); | |
1079 | /// | |
1080 | /// println!("Unpark the thread"); | |
1081 | /// parked_thread.thread().unpark(); | |
1082 | /// | |
1083 | /// parked_thread.join().unwrap(); | |
32a655c1 | 1084 | /// ``` |
85aaf69f | 1085 | #[stable(feature = "rust1", since = "1.0.0")] |
1b1a35ee | 1086 | #[inline] |
1a4d82fc | 1087 | pub fn unpark(&self) { |
1b1a35ee | 1088 | self.inner.parker.unpark(); |
1a4d82fc JJ |
1089 | } |
1090 | ||
c30ab7b3 | 1091 | /// Gets the thread's unique identifier. |
32a655c1 SL |
1092 | /// |
1093 | /// # Examples | |
1094 | /// | |
1095 | /// ``` | |
32a655c1 SL |
1096 | /// use std::thread; |
1097 | /// | |
cc61c64b XL |
1098 | /// let other_thread = thread::spawn(|| { |
1099 | /// thread::current().id() | |
1100 | /// }); | |
32a655c1 | 1101 | /// |
cc61c64b XL |
1102 | /// let other_thread_id = other_thread.join().unwrap(); |
1103 | /// assert!(thread::current().id() != other_thread_id); | |
32a655c1 | 1104 | /// ``` |
7cac9316 | 1105 | #[stable(feature = "thread_id", since = "1.19.0")] |
c30ab7b3 SL |
1106 | pub fn id(&self) -> ThreadId { |
1107 | self.inner.id | |
1108 | } | |
1109 | ||
9346a6ac | 1110 | /// Gets the thread's name. |
3157f602 | 1111 | /// |
3b2f2976 XL |
1112 | /// For more information about named threads, see |
1113 | /// [this module-level documentation][naming-threads]. | |
1114 | /// | |
3157f602 XL |
1115 | /// # Examples |
1116 | /// | |
1117 | /// Threads by default have no name specified: | |
1118 | /// | |
1119 | /// ``` | |
1120 | /// use std::thread; | |
1121 | /// | |
1122 | /// let builder = thread::Builder::new(); | |
1123 | /// | |
1124 | /// let handler = builder.spawn(|| { | |
1125 | /// assert!(thread::current().name().is_none()); | |
1126 | /// }).unwrap(); | |
1127 | /// | |
1128 | /// handler.join().unwrap(); | |
1129 | /// ``` | |
1130 | /// | |
1131 | /// Thread with a specified name: | |
1132 | /// | |
1133 | /// ``` | |
1134 | /// use std::thread; | |
1135 | /// | |
1136 | /// let builder = thread::Builder::new() | |
1137 | /// .name("foo".into()); | |
1138 | /// | |
1139 | /// let handler = builder.spawn(|| { | |
1140 | /// assert_eq!(thread::current().name(), Some("foo")) | |
1141 | /// }).unwrap(); | |
1142 | /// | |
1143 | /// handler.join().unwrap(); | |
1144 | /// ``` | |
3b2f2976 XL |
1145 | /// |
1146 | /// [naming-threads]: ./index.html#naming-threads | |
85aaf69f | 1147 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 1148 | pub fn name(&self) -> Option<&str> { |
dfeec247 | 1149 | self.cname().map(|s| unsafe { str::from_utf8_unchecked(s.to_bytes()) }) |
54a0048b SL |
1150 | } |
1151 | ||
1152 | fn cname(&self) -> Option<&CStr> { | |
f9f354fc | 1153 | self.inner.name.as_deref() |
85aaf69f SL |
1154 | } |
1155 | } | |
1156 | ||
1157 | #[stable(feature = "rust1", since = "1.0.0")] | |
1158 | impl fmt::Debug for Thread { | |
532ac7d7 | 1159 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
dfeec247 | 1160 | f.debug_struct("Thread").field("id", &self.id()).field("name", &self.name()).finish() |
1a4d82fc JJ |
1161 | } |
1162 | } | |
1163 | ||
c34b1796 | 1164 | //////////////////////////////////////////////////////////////////////////////// |
e9174d1e | 1165 | // JoinHandle |
c34b1796 AL |
1166 | //////////////////////////////////////////////////////////////////////////////// |
1167 | ||
7cac9316 XL |
1168 | /// A specialized [`Result`] type for threads. |
1169 | /// | |
1a4d82fc JJ |
1170 | /// Indicates the manner in which a thread exited. |
1171 | /// | |
60c5eb7d XL |
1172 | /// The value contained in the `Result::Err` variant |
1173 | /// is the value the thread panicked with; | |
1174 | /// that is, the argument the `panic!` macro was called with. | |
1175 | /// Unlike with normal errors, this value doesn't implement | |
1176 | /// the [`Error`](crate::error::Error) trait. | |
1177 | /// | |
1178 | /// Thus, a sensible way to handle a thread panic is to either: | |
1179 | /// 1. `unwrap` the `Result<T>`, propagating the panic | |
1180 | /// 2. or in case the thread is intended to be a subsystem boundary | |
1181 | /// that is supposed to isolate system-level failures, | |
1182 | /// match on the `Err` variant and handle the panic in an appropriate way. | |
1183 | /// | |
1a4d82fc | 1184 | /// A thread that completes without panicking is considered to exit successfully. |
7cac9316 XL |
1185 | /// |
1186 | /// # Examples | |
1187 | /// | |
1188 | /// ```no_run | |
1189 | /// use std::thread; | |
1190 | /// use std::fs; | |
1191 | /// | |
1192 | /// fn copy_in_thread() -> thread::Result<()> { | |
1193 | /// thread::spawn(move || { fs::copy("foo.txt", "bar.txt").unwrap(); }).join() | |
1194 | /// } | |
1195 | /// | |
1196 | /// fn main() { | |
1197 | /// match copy_in_thread() { | |
1198 | /// Ok(_) => println!("this is fine"), | |
1199 | /// Err(_) => println!("thread panicked"), | |
1200 | /// } | |
1201 | /// } | |
1202 | /// ``` | |
1203 | /// | |
3dfed10e | 1204 | /// [`Result`]: crate::result::Result |
85aaf69f | 1205 | #[stable(feature = "rust1", since = "1.0.0")] |
532ac7d7 | 1206 | pub type Result<T> = crate::result::Result<T, Box<dyn Any + Send + 'static>>; |
1a4d82fc | 1207 | |
d9579d0f AL |
1208 | // This packet is used to communicate the return value between the child thread |
1209 | // and the parent thread. Memory is shared through the `Arc` within and there's | |
1210 | // no need for a mutex here because synchronization happens with `join()` (the | |
1211 | // parent thread never reads this packet until the child has exited). | |
1212 | // | |
1213 | // This packet itself is then stored into a `JoinInner` which in turns is placed | |
1214 | // in `JoinHandle` and `JoinGuard`. Due to the usage of `UnsafeCell` we need to | |
1215 | // manually worry about impls like Send and Sync. The type `T` should | |
1216 | // already always be Send (otherwise the thread could not have been created) and | |
1217 | // this type is inherently Sync because no methods take &self. Regardless, | |
1218 | // however, we add inheriting impls for Send/Sync to this type to ensure it's | |
1219 | // Send/Sync and that future modifications will still appropriately classify it. | |
1a4d82fc JJ |
1220 | struct Packet<T>(Arc<UnsafeCell<Option<Result<T>>>>); |
1221 | ||
d9579d0f AL |
1222 | unsafe impl<T: Send> Send for Packet<T> {} |
1223 | unsafe impl<T: Sync> Sync for Packet<T> {} | |
1a4d82fc | 1224 | |
e9174d1e | 1225 | /// Inner representation for JoinHandle |
85aaf69f | 1226 | struct JoinInner<T> { |
d9579d0f | 1227 | native: Option<imp::Thread>, |
85aaf69f SL |
1228 | thread: Thread, |
1229 | packet: Packet<T>, | |
85aaf69f SL |
1230 | } |
1231 | ||
1232 | impl<T> JoinInner<T> { | |
1233 | fn join(&mut self) -> Result<T> { | |
d9579d0f | 1234 | self.native.take().unwrap().join(); |
dfeec247 | 1235 | unsafe { (*self.packet.0.get()).take().unwrap() } |
85aaf69f SL |
1236 | } |
1237 | } | |
1238 | ||
1239 | /// An owned permission to join on a thread (block on its termination). | |
1240 | /// | |
7cac9316 XL |
1241 | /// A `JoinHandle` *detaches* the associated thread when it is dropped, which |
1242 | /// means that there is no longer any handle to thread and no way to `join` | |
1243 | /// on it. | |
85aaf69f | 1244 | /// |
32a655c1 | 1245 | /// Due to platform restrictions, it is not possible to [`Clone`] this |
7cac9316 | 1246 | /// handle: the ability to join a thread is a uniquely-owned permission. |
3157f602 XL |
1247 | /// |
1248 | /// This `struct` is created by the [`thread::spawn`] function and the | |
1249 | /// [`thread::Builder::spawn`] method. | |
1250 | /// | |
1251 | /// # Examples | |
1252 | /// | |
1253 | /// Creation from [`thread::spawn`]: | |
1254 | /// | |
32a655c1 | 1255 | /// ``` |
3157f602 XL |
1256 | /// use std::thread; |
1257 | /// | |
1258 | /// let join_handle: thread::JoinHandle<_> = thread::spawn(|| { | |
1259 | /// // some work here | |
1260 | /// }); | |
1261 | /// ``` | |
1262 | /// | |
1263 | /// Creation from [`thread::Builder::spawn`]: | |
1264 | /// | |
32a655c1 | 1265 | /// ``` |
3157f602 XL |
1266 | /// use std::thread; |
1267 | /// | |
1268 | /// let builder = thread::Builder::new(); | |
1269 | /// | |
1270 | /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| { | |
1271 | /// // some work here | |
1272 | /// }).unwrap(); | |
1273 | /// ``` | |
1274 | /// | |
7cac9316 XL |
1275 | /// Child being detached and outliving its parent: |
1276 | /// | |
1277 | /// ```no_run | |
1278 | /// use std::thread; | |
1279 | /// use std::time::Duration; | |
1280 | /// | |
1281 | /// let original_thread = thread::spawn(|| { | |
1282 | /// let _detached_thread = thread::spawn(|| { | |
1283 | /// // Here we sleep to make sure that the first thread returns before. | |
1284 | /// thread::sleep(Duration::from_millis(10)); | |
1285 | /// // This will be called, even though the JoinHandle is dropped. | |
1286 | /// println!("♫ Still alive ♫"); | |
1287 | /// }); | |
1288 | /// }); | |
1289 | /// | |
abe05a73 | 1290 | /// original_thread.join().expect("The thread being joined has panicked"); |
7cac9316 XL |
1291 | /// println!("Original thread is joined."); |
1292 | /// | |
1293 | /// // We make sure that the new thread has time to run, before the main | |
1294 | /// // thread returns. | |
1295 | /// | |
1296 | /// thread::sleep(Duration::from_millis(1000)); | |
1297 | /// ``` | |
1298 | /// | |
3dfed10e XL |
1299 | /// [`thread::Builder::spawn`]: Builder::spawn |
1300 | /// [`thread::spawn`]: spawn | |
85aaf69f | 1301 | #[stable(feature = "rust1", since = "1.0.0")] |
9346a6ac | 1302 | pub struct JoinHandle<T>(JoinInner<T>); |
85aaf69f | 1303 | |
8faf50e0 XL |
1304 | #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")] |
1305 | unsafe impl<T> Send for JoinHandle<T> {} | |
1306 | #[stable(feature = "joinhandle_impl_send_sync", since = "1.29.0")] | |
1307 | unsafe impl<T> Sync for JoinHandle<T> {} | |
1308 | ||
9346a6ac | 1309 | impl<T> JoinHandle<T> { |
32a655c1 SL |
1310 | /// Extracts a handle to the underlying thread. |
1311 | /// | |
1312 | /// # Examples | |
1313 | /// | |
1314 | /// ``` | |
32a655c1 SL |
1315 | /// use std::thread; |
1316 | /// | |
1317 | /// let builder = thread::Builder::new(); | |
1318 | /// | |
1319 | /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| { | |
1320 | /// // some work here | |
1321 | /// }).unwrap(); | |
1322 | /// | |
1323 | /// let thread = join_handle.thread(); | |
1324 | /// println!("thread id: {:?}", thread.id()); | |
1325 | /// ``` | |
85aaf69f SL |
1326 | #[stable(feature = "rust1", since = "1.0.0")] |
1327 | pub fn thread(&self) -> &Thread { | |
1328 | &self.0.thread | |
1329 | } | |
1330 | ||
9346a6ac | 1331 | /// Waits for the associated thread to finish. |
85aaf69f | 1332 | /// |
b7449926 XL |
1333 | /// In terms of [atomic memory orderings], the completion of the associated |
1334 | /// thread synchronizes with this function returning. In other words, all | |
1335 | /// operations performed by that thread are ordered before all | |
1336 | /// operations that happen after `join` returns. | |
1337 | /// | |
32a655c1 | 1338 | /// If the child thread panics, [`Err`] is returned with the parameter given |
3dfed10e | 1339 | /// to [`panic!`]. |
32a655c1 | 1340 | /// |
3dfed10e XL |
1341 | /// [`Err`]: crate::result::Result::Err |
1342 | /// [atomic memory orderings]: crate::sync::atomic | |
32a655c1 | 1343 | /// |
3b2f2976 XL |
1344 | /// # Panics |
1345 | /// | |
1346 | /// This function may panic on some platforms if a thread attempts to join | |
1347 | /// itself or otherwise may create a deadlock with joining threads. | |
1348 | /// | |
32a655c1 SL |
1349 | /// # Examples |
1350 | /// | |
1351 | /// ``` | |
1352 | /// use std::thread; | |
1353 | /// | |
1354 | /// let builder = thread::Builder::new(); | |
1355 | /// | |
1356 | /// let join_handle: thread::JoinHandle<_> = builder.spawn(|| { | |
1357 | /// // some work here | |
1358 | /// }).unwrap(); | |
1359 | /// join_handle.join().expect("Couldn't join on the associated thread"); | |
1360 | /// ``` | |
85aaf69f | 1361 | #[stable(feature = "rust1", since = "1.0.0")] |
9346a6ac | 1362 | pub fn join(mut self) -> Result<T> { |
85aaf69f SL |
1363 | self.0.join() |
1364 | } | |
1365 | } | |
1366 | ||
92a42be0 | 1367 | impl<T> AsInner<imp::Thread> for JoinHandle<T> { |
dfeec247 XL |
1368 | fn as_inner(&self) -> &imp::Thread { |
1369 | self.0.native.as_ref().unwrap() | |
1370 | } | |
92a42be0 SL |
1371 | } |
1372 | ||
1373 | impl<T> IntoInner<imp::Thread> for JoinHandle<T> { | |
dfeec247 XL |
1374 | fn into_inner(self) -> imp::Thread { |
1375 | self.0.native.unwrap() | |
1376 | } | |
92a42be0 SL |
1377 | } |
1378 | ||
8bb4bdeb | 1379 | #[stable(feature = "std_debug", since = "1.16.0")] |
32a655c1 | 1380 | impl<T> fmt::Debug for JoinHandle<T> { |
532ac7d7 | 1381 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
32a655c1 SL |
1382 | f.pad("JoinHandle { .. }") |
1383 | } | |
1384 | } | |
1385 | ||
d9579d0f AL |
1386 | fn _assert_sync_and_send() { |
1387 | fn _assert_both<T: Send + Sync>() {} | |
1388 | _assert_both::<JoinHandle<()>>(); | |
d9579d0f AL |
1389 | _assert_both::<Thread>(); |
1390 | } |