Skip to main content

std/thread/
builder.rs

1use super::join_handle::JoinHandle;
2use super::lifecycle::spawn_unchecked;
3use crate::io;
4
5/// Thread factory, which can be used in order to configure the properties of
6/// a new thread.
7///
8/// Methods can be chained on it in order to configure it.
9///
10/// The two configurations available are:
11///
12/// - [`name`]: specifies an [associated name for the thread][naming-threads]
13/// - [`stack_size`]: specifies the [desired stack size for the thread][stack-size]
14///
15/// The [`spawn`] method will take ownership of the builder and create an
16/// [`io::Result`] to the thread handle with the given configuration.
17///
18/// The [`thread::spawn`] free function uses a `Builder` with default
19/// configuration and [`unwrap`]s its return value.
20///
21/// You may want to use [`spawn`] instead of [`thread::spawn`], when you want
22/// to recover from a failure to launch a thread, indeed the free function will
23/// panic where the `Builder` method will return a [`io::Result`].
24///
25/// # Examples
26///
27/// ```
28/// use std::thread;
29///
30/// let builder = thread::Builder::new();
31///
32/// let handler = builder.spawn(|| {
33///     // thread code
34/// }).unwrap();
35///
36/// handler.join().unwrap();
37/// ```
38///
39/// [`stack_size`]: Builder::stack_size
40/// [`name`]: Builder::name
41/// [`spawn`]: Builder::spawn
42/// [`thread::spawn`]: super::spawn
43/// [`unwrap`]: crate::result::Result::unwrap
44/// [naming-threads]: ./index.html#naming-threads
45/// [stack-size]: ./index.html#stack-size
46#[must_use = "must eventually spawn the thread"]
47#[stable(feature = "rust1", since = "1.0.0")]
48#[derive(Debug)]
49pub struct Builder {
50    /// A name for the thread-to-be, for identification in panic messages
51    pub(super) name: Option<String>,
52    /// The size of the stack for the spawned thread in bytes
53    pub(super) stack_size: Option<usize>,
54    /// Skip running and inheriting the thread spawn hooks
55    pub(super) no_hooks: bool,
56}
57
58impl Builder {
59    /// Generates the base configuration for spawning a thread, from which
60    /// configuration methods can be chained.
61    ///
62    /// # Examples
63    ///
64    /// ```
65    /// use std::thread;
66    ///
67    /// let builder = thread::Builder::new()
68    ///                               .name("foo".into())
69    ///                               .stack_size(32 * 1024);
70    ///
71    /// let handler = builder.spawn(|| {
72    ///     // thread code
73    /// }).unwrap();
74    ///
75    /// handler.join().unwrap();
76    /// ```
77    #[ferrocene::prevalidated]
78    #[stable(feature = "rust1", since = "1.0.0")]
79    pub fn new() -> Builder {
80        Builder { name: None, stack_size: None, no_hooks: false }
81    }
82
83    /// Names the thread-to-be. Currently the name is used for identification
84    /// only in panic messages.
85    ///
86    /// The name must not contain null bytes (`\0`).
87    ///
88    /// For more information about named threads, see
89    /// [this module-level documentation][naming-threads].
90    ///
91    /// # Examples
92    ///
93    /// ```
94    /// use std::thread;
95    ///
96    /// let builder = thread::Builder::new()
97    ///     .name("foo".into());
98    ///
99    /// let handler = builder.spawn(|| {
100    ///     assert_eq!(thread::current().name(), Some("foo"))
101    /// }).unwrap();
102    ///
103    /// handler.join().unwrap();
104    /// ```
105    ///
106    /// [naming-threads]: ./index.html#naming-threads
107    #[stable(feature = "rust1", since = "1.0.0")]
108    pub fn name(mut self, name: String) -> Builder {
109        self.name = Some(name);
110        self
111    }
112
113    /// Sets the size of the stack (in bytes) for the new thread.
114    ///
115    /// The actual stack size may be greater than this value if
116    /// the platform specifies a minimal stack size.
117    ///
118    /// For more information about the stack size for threads, see
119    /// [this module-level documentation][stack-size].
120    ///
121    /// # Examples
122    ///
123    /// ```
124    /// use std::thread;
125    ///
126    /// let builder = thread::Builder::new().stack_size(32 * 1024);
127    /// ```
128    ///
129    /// [stack-size]: ./index.html#stack-size
130    #[stable(feature = "rust1", since = "1.0.0")]
131    pub fn stack_size(mut self, size: usize) -> Builder {
132        self.stack_size = Some(size);
133        self
134    }
135
136    /// Disables running and inheriting [spawn hooks].
137    ///
138    /// Use this if the parent thread is in no way relevant for the child thread.
139    /// For example, when lazily spawning threads for a thread pool.
140    ///
141    /// [spawn hooks]: super::add_spawn_hook
142    #[unstable(feature = "thread_spawn_hook", issue = "132951")]
143    pub fn no_hooks(mut self) -> Builder {
144        self.no_hooks = true;
145        self
146    }
147
148    /// Spawns a new thread by taking ownership of the `Builder`, and returns an
149    /// [`io::Result`] to its [`JoinHandle`].
150    ///
151    /// The spawned thread may outlive the caller (unless the caller thread
152    /// is the main thread; the whole process is terminated when the main
153    /// thread finishes). The join handle can be used to block on
154    /// termination of the spawned thread, including recovering its panics.
155    ///
156    /// For a more complete documentation see [`thread::spawn`].
157    ///
158    /// # Errors
159    ///
160    /// Unlike the [`spawn`] free function, this method yields an
161    /// [`io::Result`] to capture any failure to create the thread at
162    /// the OS level.
163    ///
164    /// # Panics
165    ///
166    /// Panics if a thread name was set and it contained null bytes.
167    ///
168    /// # Examples
169    ///
170    /// ```
171    /// use std::thread;
172    ///
173    /// let builder = thread::Builder::new();
174    ///
175    /// let handler = builder.spawn(|| {
176    ///     // thread code
177    /// }).unwrap();
178    ///
179    /// handler.join().unwrap();
180    /// ```
181    ///
182    /// [`thread::spawn`]: super::spawn
183    /// [`spawn`]: super::spawn
184    #[ferrocene::prevalidated]
185    #[stable(feature = "rust1", since = "1.0.0")]
186    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
187    pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
188    where
189        F: FnOnce() -> T,
190        F: Send + 'static,
191        T: Send + 'static,
192    {
193        unsafe { self.spawn_unchecked(f) }
194    }
195
196    /// Spawns a new thread without any lifetime restrictions by taking ownership
197    /// of the `Builder`, and returns an [`io::Result`] to its [`JoinHandle`].
198    ///
199    /// The spawned thread may outlive the caller (unless the caller thread
200    /// is the main thread; the whole process is terminated when the main
201    /// thread finishes). The join handle can be used to block on
202    /// termination of the spawned thread, including recovering its panics.
203    ///
204    /// This method is identical to [`thread::Builder::spawn`][`Builder::spawn`],
205    /// except for the relaxed lifetime bounds, which render it unsafe.
206    /// For a more complete documentation see [`thread::spawn`].
207    ///
208    /// # Errors
209    ///
210    /// Unlike the [`spawn`] free function, this method yields an
211    /// [`io::Result`] to capture any failure to create the thread at
212    /// the OS level.
213    ///
214    /// # Panics
215    ///
216    /// Panics if a thread name was set and it contained null bytes.
217    ///
218    /// # Safety
219    ///
220    /// The caller has to ensure that the spawned thread does not outlive any
221    /// references in the supplied thread closure and its return type.
222    /// This can be guaranteed in two ways:
223    ///
224    /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced
225    /// data is dropped
226    /// - use only types with `'static` lifetime bounds, i.e., those with no or only
227    /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`]
228    /// and [`thread::spawn`] enforce this property statically)
229    ///
230    /// # Examples
231    ///
232    /// ```
233    /// use std::thread;
234    ///
235    /// let builder = thread::Builder::new();
236    ///
237    /// let x = 1;
238    /// let thread_x = &x;
239    ///
240    /// let handler = unsafe {
241    ///     builder.spawn_unchecked(move || {
242    ///         println!("x = {}", *thread_x);
243    ///     }).unwrap()
244    /// };
245    ///
246    /// // caller has to ensure `join()` is called, otherwise
247    /// // it is possible to access freed memory if `x` gets
248    /// // dropped before the thread closure is executed!
249    /// handler.join().unwrap();
250    /// ```
251    ///
252    /// [`thread::spawn`]: super::spawn
253    /// [`spawn`]: super::spawn
254    #[ferrocene::prevalidated]
255    #[stable(feature = "thread_spawn_unchecked", since = "1.82.0")]
256    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
257    pub unsafe fn spawn_unchecked<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
258    where
259        F: FnOnce() -> T,
260        F: Send,
261        T: Send,
262    {
263        let Builder { name, stack_size, no_hooks } = self;
264        Ok(JoinHandle(unsafe { spawn_unchecked(name, stack_size, no_hooks, None, f) }?))
265    }
266}