about summary refs log tree commit diff
path: root/library/std/src/thread/mod.rs
AgeCommit message (Collapse)AuthorLines
2025-07-06sleep_until: use clock_nanosleep where possibledvdsk-8/+27
Using clock nanosleep leads to more accurate sleep times on platforms where it is supported. To enable using clock_nanosleep this makes `sleep_until` platform specific. That unfortunatly requires identical placeholder implementations for the other platforms (windows/mac/wasm etc). we will land platform specific implementations for those later. See the `sleep_until` tracking issue. This requires an accessors for the Instant type. As that accessor is only used on the platforms that have clock_nanosleep it is marked as allow_unused. 32bit time_t targets do not use clock_nanosleep atm, they instead rely on the same placeholder as the other platforms. We could make them use clock_nanosleep too in the future using `__clock_nanosleep_time64`. __clock_nanosleep_time64 is documented at: https://www.gnu.org/software/libc/manual/html_node/64_002dbit-time-symbol-handling.html
2025-05-12update cfg(bootstrap)Pietro Albini-1/+1
2025-04-27use generic Atomic type where possibleChristopher Durham-8/+8
in core/alloc/std only for now, and ignoring test files Co-authored-by: Pavel Grigorenko <GrigorenkoPV@ya.ru>
2025-04-11rustdoc-search: add unbox flag to Result aliasesMichael Howell-0/+1
Fixes #139665
2025-02-25Use `.expect(..)` insteadMahmoud Mazouz-5/+10
2025-02-24Remove speculation on cause of errorMahmoud Mazouz-1/+1
Co-authored-by: Jubilee <workingjubilee@gmail.com>
2025-02-23Return error on unexpected termination in `Thread::join`.Mahmoud Mazouz-1/+5
There is a time window during which the OS can terminate a thread before stdlib can retreive its `Packet`. Currently the `Thread::join` panics with no message in such an event, which makes debugging difficult; fixes #124466.
2025-01-14add comments explaining main thread identificationjoboet-0/+26
2025-01-14std: lazily allocate the main thread handlejoboet-51/+99
Thereby, we also allow accessing thread::current before main: as the runtime no longer tries to install its own handle, this will no longer trigger an abort. Rather, the name returned from name will only be "main" after the runtime initialization code has run, but I think that is acceptable. This new approach also requires some changes to the signal handling code, as calling `thread::current` would now allocate when called on the main thread, which is not acceptable. I fixed this by adding a new function (`with_current_name`) that performs all the naming logic without allocation or without initializing the thread ID (which could allocate on some platforms).
2025-01-14Revert "Remove the Arc rt::init allocation for thread info"joboet-117/+53
This reverts commit 0747f2898e83df7e601189c0f31762e84328becb.
2025-01-08Remove some unnecessary `.into()` callsEsteban Küber-1/+1
2024-12-20mri: add track_caller to thread spawning methods for better backtracesRalf Jung-0/+4
2024-12-03Rollup merge of #132937 - xmh0511:master, r=m-ou-seMatthias Krüger-3/+3
a release operation synchronizes with an acquire operation Change: 1. `Calls to park _synchronize-with_ calls to unpark` to `Calls to unpark _synchronize-with_ calls to park` 2. `park synchronizes-with _all_ prior unpark operations` to `_all_ prior unpark operations synchronize-with park`
2024-11-25Rollup merge of #132730 - joboet:after_main_sync, r=Noratrieb许杰友 Jieyou Xu (Joe)-3/+12
std: allow after-main use of synchronization primitives By creating an unnamed thread handle when the actual one has already been destroyed, synchronization primitives using thread parking can be used even outside the Rust runtime. This also fixes an inefficiency in the queue-based `RwLock`: if `thread::current` was not initialized yet, it will create a new handle on every parking attempt without initializing `thread::current`. The private `current_or_unnamed` function introduced here fixes this.
2024-11-19Add tracking issue.Mara Bos-2/+2
2024-11-19Add thread Builder::no_hooks().Mara Bos-3/+19
2024-11-19Update thread spawn hooks.Mara Bos-5/+2
1. Make the effect thread local. 2. Don't return a io::Result from hooks.
2024-11-19Use add_spawn_hook for libtest's output capturing.Mara Bos-4/+0
2024-11-19Add std::thread::add_spawn_hook.Mara Bos-0/+11
2024-11-18std: allow after-main use of synchronization primitivesjoboet-3/+12
By creating an unnamed thread handle when the actual one has already been destroyed, synchronization primitives using thread parking can be used even outside the Rust runtime. This also fixes an inefficiency in the queue-based `RwLock`: if `thread::current` was not initialized yet, it will create a new handle on every parking attempt without initializing `thread::current`. The private `current_or_unnamed` function introduced here fixes this.
2024-11-12a release operation synchronizes with an acquire operationxmh0511-3/+3
2024-10-25library: consistently use American spelling for 'behavior'Ralf Jung-2/+2
2024-10-19Remove the Arc rt::init allocation for thread infoGnomedDev-53/+117
2024-10-12std: fix stdout-before-mainjoboet-11/+13
Fixes #130210. Since #124881, `ReentrantLock` uses `ThreadId` to identify threads. This has the unfortunate consequence of breaking uses of `Stdout` before main: Locking the `ReentrantLock` that synchronizes the output will initialize the thread ID before the handle for the main thread is set in `rt::init`. But since that would overwrite the current thread ID, `thread::set_current` triggers an abort. This PR fixes the problem by using the already initialized thread ID for constructing the main thread handle and allowing `set_current` calls that do not change the thread's ID.
2024-10-02std: make `thread::current` available in all `thread_local!` destructorsjoboet-93/+35
2024-09-30Rollup merge of #129638 - nickrum:wasip2-net, r=alexcrichtonTrevor Gross-1/+1
Hook up std::net to wasi-libc on wasm32-wasip2 target One of the improvements of the `wasm32-wasip2` target over `wasm32-wasip1` is better support for networking. Right now, p2 is just re-using the `std::net` implementation from p1. This PR adds a new net module for p2 that makes use of net from `sys_common` and calls wasi-libc functions directly. There are currently a few limitations: - Duplicating a socket is not supported by WASIp2 (directly returns an error) - Peeking is not yet implemented in wasi-libc (we could let wasi-libc handle this, but I opted to directly return an error instead) - Vectored reads/writes are not supported by WASIp2 (the necessary functions are available in wasi-libc, but they call WASIp1 functions which do not support sockets, so I opted to directly return an error instead) - Getting/setting `TCP_NODELAY` is faked in wasi-libc (uses the fake implementation instead of returning an error) - Getting/setting `SO_LINGER` is not supported by WASIp2 (directly returns an error) - Setting `SO_REUSEADDR` is faked in wasi-libc (since this is done from `sys_common`, the fake implementation is used instead of returning an error) - Getting/setting `IPV6_V6ONLY` is not supported by WASIp2 and will always be set for IPv6 sockets (since this is done from `sys_common`, wasi-libc will return an error) - UDP broadcast/multicast is not supported by WASIp2 (since this is configured from `sys_common`, wasi-libc will return appropriate errors) - The `MSG_NOSIGNAL` send flag is a no-op because there are no signals in WASIp2 (since explicitly setting this flag would require a change to `sys_common` and the result would be exactly the same, I opted to not set it) Do those decisions make sense? While working on this PR, I noticed that there is a `std::os::wasi::net::TcpListenerExt` trait that adds a `sock_accept()` method to `std::net::TcpListener`. Now that WASIp2 supports standard accept, would it make sense to remove this? cc `@alexcrichton`
2024-09-29Auto merge of #128321 - BatmanAoD:catch-unwind-doc-update, r=Mark-Simulacrumbors-1/+26
Update `catch_unwind` doc comments for `c_unwind` Updates `catch_unwind` doc comments to indicate that catching a foreign exception _will no longer_ be UB. Instead, there are two possible behaviors, though it is not specified which one an implementation will choose. Nominated for t-lang to confirm that they are okay with making such a promise based on t-opsem FCP, or whether they would like to be included in the FCP. Related: https://github.com/rust-lang/rust/issues/74990, https://github.com/rust-lang/rust/issues/115285, https://github.com/rust-lang/reference/pull/1226
2024-09-29Fix std tests for wasm32-wasip2 targetNicola Krumschmidt-1/+1
2024-09-25Use `&raw` in the standard libraryJosh Stone-4/+3
Since the stabilization in #127679 has reached stage0, 1.82-beta, we can start using `&raw` freely, and even the soft-deprecated `ptr::addr_of!` and `ptr::addr_of_mut!` can stop allowing the unstable feature. I intentionally did not change any documentation or tests, but the rest of those macro uses are all now using `&raw const` or `&raw mut` in the standard library.
2024-09-22Reformat using the new identifier sorting from rustfmtMichael Goulet-3/+3
2024-09-18Rollup merge of #97524 - ibraheemdev:thread-raw, r=ibraheemdevJubilee-0/+48
Add `Thread::{into_raw, from_raw}` Public API: ```rust #![unstable(feature = "thread_raw", issue = "97523")] impl Thread { pub fn into_raw(self) -> *const (); pub unsafe fn from_raw(ptr: *const ()) -> Thread; } ``` ACP: https://github.com/rust-lang/libs-team/issues/200
2024-09-17add `Thread::{into_raw, from_raw}`Ibraheem Ahmed-0/+48
2024-09-15update docs for `catch_unwind` & related funcsKyle J Strand-1/+26
Documentation comments for `catch_unwind` and `thread::join` to indicate new behavioral guarantee when catching a foreign exception.
2024-09-03replace placeholder versionBoxy-1/+1
2024-08-16Stabilize std::thread::Builder::spawn_uncheckedDavid Tolnay-2/+1
2024-08-06Remove unused lifetime parameter from spawn_uncheckedDavid Tolnay-8/+7
2024-07-29Reformat `use` declarations.Nicholas Nethercote-7/+3
The previous commit updated `rustfmt.toml` appropriately. This commit is the outcome of running `x fmt --all` with the new formatting options.
2024-07-26Fix doc nitsJohn Arundel-2/+2
Many tiny changes to stdlib doc comments to make them consistent (for example "Returns foo", rather than "Return foo", per RFC1574), adding missing periods, paragraph breaks, backticks for monospace style, and other minor nits. https://github.com/rust-lang/rfcs/blob/master/text/1574-more-api-documentation-conventions.md#appendix-a-full-conventions-text
2024-07-24Rollup merge of #128135 - joboet:reduplicate_tls, r=tgross35Matthias Krüger-16/+8
std: use duplicate thread local state in tests With rust-lang/miri#3739 merged, the deduplication hack is no longer necessary.
2024-07-24Rollup merge of #127733 - GrigorenkoPV:don't-forget, r=AmanieuMatthias Krüger-5/+4
Replace some `mem::forget`'s with `ManuallyDrop` > but I would like to see a larger effort to replace all uses of `mem::forget`. _Originally posted by `@saethlin` in https://github.com/rust-lang/rust/issues/127584#issuecomment-2226087767_ So, r? `@saethlin` Sorry, I have finished writing all of this before I got your response.
2024-07-24std: use duplicate thread local state in testsjoboet-16/+8
With rust-lang/miri#3739 merged, the deduplication hack is no longer necessary.
2024-07-20Rollup merge of #127918 - ChrisDenton:thread-name-string, r=joboetMatthias Krüger-23/+51
Safely enforce thread name requirements The requirements for the thread name to be both UTF-8 and null terminated are easily enforced by a wrapper type so lets do that. The fact this used to be just a bare `CString` has tripped me up before because it was entirely safe to use a non UTF-8 `CString`.
2024-07-18Move ThreadName conversions to &cstr/&strChris Denton-6/+19
2024-07-18Style changeChris Denton-3/+3
2024-07-18Make `Thread::new_inner` a safe functionChris Denton-6/+4
2024-07-18Rollup merge of #124881 - Sp00ph:reentrant_lock_tid, r=joboetMatthias Krüger-3/+29
Use ThreadId instead of TLS-address in `ReentrantLock` Fixes #123458 `ReentrantLock` currently uses the address of a thread local variable as an ID that's unique across all currently running threads. This can lead to uninituitive behavior as in #123458 if TLS blocks get reused. This PR changes `ReentrantLock` to instead use the `ThreadId` provided by `std` as the unique ID. `ThreadId` guarantees uniqueness across the lifetime of the whole process, so we don't need to worry about reusing IDs of terminated threads. The main appeal of this PR is thus the possibility of changing the `ReentrantLock` API to guarantee that if a thread leaks a lock guard, no other thread may ever acquire that lock again. This does entail some complications: - previously, the only way to retrieve the current thread ID would've been using `thread::current().id()` which creates a temporary `Arc` and which isn't available in TLS destructors. As part of this PR, the thread ID instead gets cached in its own thread local, as suggested [here](https://github.com/rust-lang/rust/issues/123458#issuecomment-2038207704). - `ThreadId` is always 64-bit whereas the current implementation uses a usize-sized ID. Since this ID needs to be updated atomically, we can't simply use a single atomic variable on 32 bit platforms. Instead, we fall back to using a (sound) seqlock on 32-bit platforms, which works because only one thread at a time can write to the ID. This seqlock is technically susceptible to the ABA problem, but the attack vector to create actual unsoundness has to be very specific: - You would need to be able to lock+unlock the lock exactly 2^31 times (or a multiple thereof) while a thread trying to lock it sleeps - The sleeping thread would have to suspend after reading one half of the thread id but before reading the other half - The teared result from combining the halves of the thread ID would have to exactly line up with the sleeping thread's ID The risk of this occurring seems slim enough to be acceptable to me, but correct me if I'm wrong. This also means that the size of the lock increases by 8 bytes on 32-bit platforms, but this also shouldn't be an issue. Performance wise, I did some crude testing of the only case where this could lead to real slowdowns, which is the case of locking a `ReentrantLock` that's already locked by the current thread. On both aarch64 and x86-64, there is (expectedly) pretty much no performance hit. I didn't have any 32-bit platforms to test the seqlock performance on, so I did the next best thing and just forced the 64-bit platforms to use the seqlock implementation. There, the performance degraded by ~1-2ns/(lock+unlock) on x86-64 and ~6-8ns/(lock+unlock) on aarch64, which is measurable but seems acceptable to me seeing as 32-bit platforms should be a small minority anyways. cc `@joboet` `@RalfJung` `@CAD97`
2024-07-18Update `ReentrantLock` implementation, add `CURRENT_ID` thread local.Markus Everling-3/+29
This changes `ReentrantLock` to use `ThreadId` for the thread ownership check instead of the address of a thread local. Unlike TLS blocks, `ThreadId` is guaranteed to be unique across the lifetime of the process, so if any thread ever terminates while holding a `ReentrantLockGuard`, no other thread may ever acquire that lock again. On platforms with 64-bit atomics, this is a very simple change. On other platforms, the approach used is slightly more involved, as explained in the module comment. This also adds a `CURRENT_ID` thread local in addition to the already existing `CURRENT`. This allows us to access the current `ThreadId` without the relatively heavy machinery used by `thread::current().id()`.
2024-07-18Safely enforce thread name requirementsChris Denton-11/+28
2024-07-15lib: replace some `mem::forget`'s with `ManuallyDrop`Pavel Grigorenko-5/+4
2024-06-16std: move `sys_common::backtrace` to `sys`joboet-1/+1