about summary refs log tree commit diff
path: root/library/std/src/thread/mod.rs
AgeCommit message (Collapse)AuthorLines
2022-01-23Rollup merge of #92555 - m-ou-se:scoped-threads, r=AmanieuMatthias Krüger-27/+66
Implement RFC 3151: Scoped threads. This implements https://github.com/rust-lang/rfcs/pull/3151 r? `@Amanieu`
2022-01-22Add tracking issue number for scoped_threads.Mara Bos-2/+2
2022-01-22Simplify Send/Sync of std::thread::Packet.Mara Bos-7/+5
2022-01-13Auto merge of #92553 - m-ou-se:thread-join-simplify, r=Mark-Simulacrumbors-9/+9
Simpilfy thread::JoinInner. `JoinInner`'s `native` field was an `Option`, but that's unnecessary. Also, thanks to `Arc::get_mut`, there's no unsafety needed in `JoinInner::join()`.
2022-01-07Stabilize `#[feature(available_parallelism)]`Yoshua Wuyts-2/+1
2022-01-05Rename n_running_threads to num_running_threads.Mara Bos-2/+2
2022-01-04Fix typo in is_running() docs.Mara Bos-1/+1
Co-authored-by: Mattias Buelens <649348+MattiasBuelens@users.noreply.github.com>
2022-01-04Simplify panicking mechanism of thread::scope.Mara Bos-8/+5
It now panic!()s on its own, rather than resume_unwind'ing the panic payload from the thread. Using resume_unwind skips the panic_handler, meaning that the main thread would never have a panic handler run, which can get confusing.
2022-01-04Implement RFC 3151: Scoped threads.Mara Bos-26/+70
2022-01-04Simpilfy thread::JoinInner.Mara Bos-9/+9
2022-01-01Rollup merge of #84083 - ltratt:threadid_doc_tweak, r=dtolnayMatthias Krüger-4/+7
Clarify the guarantees that ThreadId does and doesn't make. The existing documentation does not spell out whether `ThreadId`s are unique during the lifetime of a thread or of a process. I had to examine the source code to realise (pleasingly!) that they're unique for the lifetime of a process. That seems worth documenting clearly, as it's a strong guarantee. Examining the way `ThreadId`s are created also made me realise that the `as_u64` method on `ThreadId` could be a trap for the unwary on those platforms where the platform's notion of a thread identifier is also a 64 bit integer (particularly if they happen to use a similar identifier scheme to `ThreadId`). I therefore think it's worth being even clearer that there's no relationship between the two.
2021-12-25Language tweak.Laurence Tratt-2/+2
2021-12-20JoinHandle docs: add missing 'the'Ralf Jung-1/+1
2021-11-29std: Stabilize the `thread_local_const_init` featureAlex Crichton-7/+0
This commit is intended to follow the stabilization disposition of the FCP that has now finished in #84223. This stabilizes the ability to flag thread local initializers as `const` expressions which enables the macro to generate more efficient code for accessing it, notably removing runtime checks for initialization. More information can also be found in #84223 as well as the tests where the feature usage was removed in this PR. Closes #84223
2021-11-19Expand available_parallelism docs in anticipation of cgroup quotasThe8472-3/+6
The "fixed" in "fixed steady state limits" means to exclude load-dependent resource prioritization that would calculate to 100% of capacity on an idle system and less capacity on a loaded system. Additionally I also exclude "system load" since it would be silly to try to identify other, perhaps higher priority, processes hogging some CPU cores that aren't explicitly excluded by masks/quotas/whatever.
2021-11-10Use `target_family = "wasm"`Alex Crichton-4/+1
2021-11-10std: Get the standard library compiling for wasm64Alex Crichton-1/+4
This commit goes through and updates various `#[cfg]` as appropriate to get the wasm64-unknown-unknown target behaving similarly to the wasm32-unknown-unknown target. Most of this is just updating various conditions for `target_arch = "wasm32"` to also account for `target_arch = "wasm64"` where appropriate. This commit also lists `wasm64` as an allow-listed architecture to not have the `restricted_std` feature enabled, enabling experimentation with `-Z build-std` externally. The main goal of this commit is to enable playing around with `wasm64-unknown-unknown` externally via `-Z build-std` in a way that's similar to the `wasm32-unknown-unknown` target. These targets are effectively the same and only differ in their pointer size, but wasm64 is much newer and has much less ecosystem/library support so it'll still take time to get wasm64 fully-fledged.
2021-11-02Auto merge of #90439 - m-ou-se:thread-is-running, r=Mark-Simulacrumbors-0/+9
Add JoinHandle::is_running. This adds: ```rust impl<T> JoinHandle<T> { /// Checks if the the associated thread is still running its main function. /// /// This might return `false` for a brief moment after the thread's main /// function has returned, but before the thread itself has stopped running. pub fn is_running(&self) -> bool; } ``` The usual way to check if a background thread is still running is to set some atomic flag at the end of its main function. We already do that, in the form of dropping an Arc which will reduce the reference counter. So we might as well expose that information. This is useful in applications with a main loop (e.g. a game, gui, control system, ..) where you spawn some background task, and check every frame/iteration whether the background task is finished to .join() it in that frame/iteration while keeping the program responsive.
2021-11-01Add tracking issue for thread_is_running.Mara Bos-1/+1
2021-10-31Add JoinHandle::is_running.Mara Bos-0/+9
2021-10-31Rollup merge of #90431 - jkugelman:must-use-std-o-through-z, r=joshtriplettMatthias Krüger-0/+5
Add #[must_use] to remaining std functions (O-Z) I've run out of compelling reasons to group functions together across crates so I'm just going to go module-by-module. This is half of the remaining items from the `std` crate, from O-Z. `panicking::take_hook` has a side effect: it unregisters the current panic hook, returning it. I almost ignored it, but the documentation example shows `let _ = panic::take_hook();`, so following suit I went ahead and added a `#[must_use]`. ```rust std::panicking fn take_hook() -> Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>; ``` I added these functions that clippy did not flag: ```rust std::path::Path fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool; std::path::Path fn ends_with<P: AsRef<Path>>(&self, child: P) -> bool; std::path::Path fn with_file_name<S: AsRef<OsStr>>(&self, file_name: S) -> PathBuf; std::path::Path fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf; ``` Parent issue: #89692 r? `@joshtriplett`
2021-10-30Add #[must_use] to remaining std functions (O-Z)John Kugelman-0/+5
2021-10-31Rollup merge of #89789 - jkugelman:must-use-thread-builder, r=joshtriplettMatthias Krüger-0/+1
Add #[must_use] to thread::Builder I copied the wording of the [`fmt::Debug` builders](https://doc.rust-lang.org/src/core/fmt/builders.rs.html#444). Affects: ```rust std/src/thread/mod.rs:289:5 std::thread::Builder fn new() -> Builder; std/src/thread/mod.rs:318:5 std::thread::Builder fn name(mut self, name: String) -> Builder; std/src/thread/mod.rs:341:5 std::thread::Builder fn stack_size(mut self, size: usize) -> Builder; ``` Parent issue: #89692 r? `@joshtriplett`
2021-10-23Add caveat about changing parallelism and function call overheadThe8472-0/+4
2021-10-13Rollup merge of #89670 - yoshuawuyts:available-parallelism-docs, r=joshtriplettMatthias Krüger-20/+57
Improve `std::thread::available_parallelism` docs _Tracking issue: https://github.com/rust-lang/rust/issues/74479_ This PR reworks the documentation of `std::thread::available_parallelism`, as requested [here](https://github.com/rust-lang/rust/pull/89324#issuecomment-934343254). ## Changes The following changes are made: - We've removed prior mentions of "hardware threads" and instead centers the docs around "parallelism" as a resource available to a program. - We now provide examples of when `available_parallelism` may return numbers that differ from the number of CPU cores in the host machine. - We now mention that the amount of available parallelism may change over time. - We make note of which platform components we don't take into account which more advanced users may want to take note of. - The example has been updated, which should be a bit easier to use. - We've added a docs alias to `num-cpus` which provides similar functionality to `available_parallelism`, and is one of the most popular crates on crates.io. --- Thanks! r? `@BurntSushi`
2021-10-13Improve `std::thread::available_parallelism` docsYoshua Wuyts-20/+57
2021-10-12Update library/std/src/thread/mod.rsJohn Kugelman-1/+1
Co-authored-by: Josh Triplett <josh@joshtriplett.org>
2021-10-11Add #[must_use] to thread::BuilderJohn Kugelman-0/+1
2021-10-11Add #[must_use] to as_type conversionsJohn Kugelman-0/+1
2021-10-08Fix minor std::thread documentation typoMarcelo Diop-Gonzalez-3/+3
callers of spawn_unchecked() need to make sure that the thread not outlive references in the passed closure, not the other way around.
2021-10-06Rollup merge of #89324 - yoshuawuyts:hardware-parallelism, r=m-ou-seManish Goregaokar-5/+7
Rename `std::thread::available_conccurrency` to `std::thread::available_parallelism` _Tracking issue: https://github.com/rust-lang/rust/issues/74479_ This PR renames `std::thread::available_conccurrency` to `std::thread::available_parallelism`. ## Rationale The API was initially named `std::thread::hardware_concurrency`, mirroring the [C++ API of the same name](https://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency). We eventually decided to omit any reference to the word "hardware" after [this comment](https://github.com/rust-lang/rust/pull/74480#issuecomment-662045841). And so we ended up with `available_concurrency` instead. --- For a talk I was preparing this week I was reading through ["Understanding and expressing scalable concurrency" (A. Turon, 2013)](http://aturon.github.io/academic/turon-thesis.pdf), and the following passage stood out to me (emphasis mine): > __Concurrency is a system-structuring mechanism.__ An interactive system that deals with disparate asynchronous events is naturally structured by division into concurrent threads with disparate responsibilities. Doing so creates a better fit between problem and solution, and can also decrease the average latency of the system by preventing long-running computations from obstructing quicker ones. > __Parallelism is a resource.__ A given machine provides a certain capacity for parallelism, i.e., a bound on the number of computations it can perform simultaneously. The goal is to maximize throughput by intelligently using this resource. For interactive systems, parallelism can decrease latency as well. _Chapter 2.1: Concurrency is not Parallelism. Page 30._ --- _"Concurrency is a system-structuring mechanism. Parallelism is a resource."_ — It feels like this accurately captures the way we should be thinking about these APIs. What this API returns is not "the amount of concurrency available to the program" which is a property of the program, and thus even with just a single thread is effectively unbounded. But instead it returns "the amount of _parallelism_ available to the program", which is a resource hard-constrained by the machine's capacity (and can be further restricted by e.g. operating systems). That's why I'd like to propose we rename this API from `available_concurrency` to `available_parallelism`. This still meets the criteria we previously established of not attempting to define what exactly we mean by "hardware", "threads", and other such words. Instead we only talk about "concurrency" as an abstract resource available to our program. r? `@joshtriplett`
2021-10-04Add doc aliases to `std::thread::available_parallelism`Yoshua Wuyts-0/+2
2021-09-28Rename `std::thread::available_onccurrency` to ↵Yoshua Wuyts-5/+5
`std::thread::available_parallelism`
2021-09-16Remove an allocation from rt::initbjorn3-7/+5
Previously the thread name would first be heap allocated and then re-allocated to add a nul terminator. Now it will be heap allocated only once with nul terminator added form the start.
2021-08-07removed references to parent/child from std::thread documentationGodmar Back-31/+40
- also clarifies how thread.join and detaching of threads works - the previous prose implied that there is a relationship between a spawning thread and the thread being spawned, and that "child" threads couldn't outlive their parents unless detached, which is incorrect.
2021-07-29Fix may not to appropriate might not or must notAli Malik-2/+2
2021-07-10rename variableRalf Jung-2/+2
2021-07-10avoid reentrant lock acquire when ThreadIds run outRalf Jung-0/+1
2021-07-06rewrote documentation for thread::yield_now()Godmar Back-16/+17
The old documentation suggested the use of yield_now for repeated polling instead of discouraging it; it also made the false claim that channels are implementing using yield_now. (They are not, except for a corner case).
2021-06-21Move `available_concurrency` implementation to `sys`Christiaan Dirkx-6/+37
2021-04-21Replace all `fmt.pad` with `debug_struct`Christiaan Dirkx-1/+1
2021-04-16std: Add a variant of thread locals with const initAlex Crichton-0/+7
This commit adds a variant of the `thread_local!` macro as a new `thread_local_const_init!` macro which requires that the initialization expression is constant (e.g. could be stuck into a `const` if so desired). This form of thread local allows for a more efficient implementation of `LocalKey::with` both if the value has a destructor and if it doesn't. If the value doesn't have a destructor then `with` should desugar to exactly as-if you use `#[thread_local]` given sufficient inlining. The purpose of this new form of thread locals is to precisely be equivalent to `#[thread_local]` on platforms where possible for values which fit the bill (those without destructors). This should help close the gap in performance between `thread_local!`, which is safe, relative to `#[thread_local]`, which is not easy to use in a portable fashion.
2021-04-11Clarify the guarantees that ThreadId does and doesn't make.Laurence Tratt-4/+7
The existing documentation does not spell out whether `ThreadId`s are unique during the lifetime of a thread or of a process. I had to examine the source code to realise (pleasingly!) that they're unique for the lifetime of a process. That seems worth documenting clearly, as it's a strong guarantee. Examining the way `ThreadId`s are created also made me realise that the `as_u64` method on `ThreadId` could be a trap for the unwary on those platforms where the platform's notion of a thread identifier is also a 64 bit integer (particularly if they happen to use a similar identifier scheme to `ThreadId`). I therefore think it's worth being even clearer that there's no relationship between the two.
2021-03-27Use DebugStruct::finish_non_exhaustive() in std.Mara Bos-1/+4
2021-02-10Rollup merge of #79849 - Digital-Chaos:sleep-zero, r=m-ou-seYuki Okushi-0/+9
Clarify docs regarding sleep of zero duration Clarify that the behaviour of sleep() when given a duration of zero is actually platform specific.
2021-01-15Update library/std/src/thread/mod.rs James Wright-0/+1
Fix link reference Co-authored-by: Joshua Nelson <joshua@yottadb.com>
2021-01-15Clarify difference between unix/windows behaviourJames Wright-0/+8
Updated to specify the underlying syscalls
2020-12-18Recommend panic::resume_unwind instead of panicking.Corey Farwell-7/+12
Fixes https://github.com/rust-lang/rust/issues/79950.
2020-11-10Merge set_panic and set_print into set_output_capture.Mara Bos-3/+3
There were no use cases for setting them separately. Merging them simplifies some things.
2020-11-07Convert a bunch of intra-doc linksCamelid-1/+0