32 Thread support library [thread]

32.4 Threads [thread.threads]

32.4.1 General [thread.threads.general]

[thread.threads] describes components that can be used to create and manage threads.
[Note 1:
These threads are intended to map one-to-one with operating system threads.
— end note]

32.4.2 Header <thread> synopsis [thread.syn]

#include <compare> // see [compare.syn] namespace std { class thread; void swap(thread& x, thread& y) noexcept; // [thread.jthread.class] class jthread class jthread; namespace this_thread { thread::id get_id() noexcept; void yield() noexcept; template<class Clock, class Duration> void sleep_until(const chrono::time_point<Clock, Duration>& abs_time); template<class Rep, class Period> void sleep_for(const chrono::duration<Rep, Period>& rel_time); } }

32.4.3 Class thread [thread.thread.class]

32.4.3.1 General [thread.thread.class.general]

The class thread provides a mechanism to create a new thread of execution, to join with a thread (i.e., wait for a thread to complete), and to perform other operations that manage and query the state of a thread.
A thread object uniquely represents a particular thread of execution.
That representation may be transferred to other thread objects in such a way that no two thread objects simultaneously represent the same thread of execution.
A thread of execution is detached when no thread object represents that thread.
Objects of class thread can be in a state that does not represent a thread of execution.
[Note 1:
A thread object does not represent a thread of execution after default construction, after being moved from, or after a successful call to detach or join.
— end note]
namespace std { class thread { public: // types class id; using native_handle_type = implementation-defined; // see [thread.req.native] // construct/copy/destroy thread() noexcept; template<class F, class... Args> explicit thread(F&& f, Args&&... args); ~thread(); thread(const thread&) = delete; thread(thread&&) noexcept; thread& operator=(const thread&) = delete; thread& operator=(thread&&) noexcept; // members void swap(thread&) noexcept; bool joinable() const noexcept; void join(); void detach(); id get_id() const noexcept; native_handle_type native_handle(); // see [thread.req.native] // static members static unsigned int hardware_concurrency() noexcept; }; }

32.4.3.2 Class thread​::​id [thread.thread.id]

namespace std { class thread::id { public: id() noexcept; }; bool operator==(thread::id x, thread::id y) noexcept; strong_ordering operator<=>(thread::id x, thread::id y) noexcept; template<class charT, class traits> basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& out, thread::id id); // hash support template<class T> struct hash; template<> struct hash<thread::id>; }
An object of type thread​::​id provides a unique identifier for each thread of execution and a single distinct value for all thread objects that do not represent a thread of execution ([thread.thread.class]).
Each thread of execution has an associated thread​::​id object that is not equal to the thread​::​id object of any other thread of execution and that is not equal to the thread​::​id object of any thread object that does not represent threads of execution.
thread​::​id is a trivially copyable class ([class.prop]).
The library may reuse the value of a thread​::​id of a terminated thread that can no longer be joined.
[Note 1:
Relational operators allow thread​::​id objects to be used as keys in associative containers.
— end note]
id() noexcept;
Postconditions: The constructed object does not represent a thread of execution.
bool operator==(thread::id x, thread::id y) noexcept;
Returns: true only if x and y represent the same thread of execution or neither x nor y represents a thread of execution.
strong_ordering operator<=>(thread::id x, thread::id y) noexcept;
Let be an unspecified total ordering over thread​::​id as described in [alg.sorting].
Returns: strong_­ordering​::​less if is true.
Otherwise, strong_­ordering​::​greater if is true.
Otherwise, strong_­ordering​::​equal.
template<class charT, class traits> basic_ostream<charT, traits>& operator<< (basic_ostream<charT, traits>& out, thread::id id);
Effects: Inserts an unspecified text representation of id into out.
For two objects of type thread​::​id x and y, if x == y the thread​::​id objects have the same text representation and if x != y the thread​::​id objects have distinct text representations.
Returns: out.
template<> struct hash<thread::id>;
The specialization is enabled ([unord.hash]).

32.4.3.3 Constructors [thread.thread.constr]

thread() noexcept;
Effects: The object does not represent a thread of execution.
Postconditions: get_­id() == id().
template<class F, class... Args> explicit thread(F&& f, Args&&... args);
Constraints: remove_­cvref_­t<F> is not the same type as thread.
Mandates: The following are all true:
  • is_­constructible_­v<decay_­t<F>, F>,
  • (is_­constructible_­v<decay_­t<Args>, Args> && ...),
  • is_­move_­constructible_­v<decay_­t<F>>,
  • (is_­move_­constructible_­v<decay_­t<Args>> && ...), and
  • is_­invocable_­v<decay_­t<F>, decay_­t<Args>...>.
Preconditions: decay_­t<F> and each type in decay_­t<Args> meet the Cpp17MoveConstructible requirements.
Effects: The new thread of execution executes invoke(decay-copy(std::forward<F>(f)), decay-copy(std::forward<Args>(args))...) with the calls to decay-copy being evaluated in the constructing thread.
Any return value from this invocation is ignored.
[Note 1:
This implies that any exceptions not thrown from the invocation of the copy of f will be thrown in the constructing thread, not the new thread.
— end note]
If the invocation of invoke terminates with an uncaught exception, terminate is called.
Synchronization: The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.
Postconditions: get_­id() != id().
*this represents the newly started thread.
Throws: system_­error if unable to start the new thread.
Error conditions:
  • resource_­unavailable_­try_­again — the system lacked the necessary resources to create another thread, or the system-imposed limit on the number of threads in a process would be exceeded.
thread(thread&& x) noexcept;
Postconditions: x.get_­id() == id() and get_­id() returns the value of x.get_­id() prior to the start of construction.

32.4.3.4 Destructor [thread.thread.destr]

~thread();
Effects: If joinable(), calls terminate().
Otherwise, has no effects.
[Note 1:
Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is thrown.
These bugs can be avoided by ensuring that the destructor is never executed while the thread is still joinable.
— end note]

32.4.3.5 Assignment [thread.thread.assign]

thread& operator=(thread&& x) noexcept;
Effects: If joinable(), calls terminate().
Otherwise, assigns the state of x to *this and sets x to a default constructed state.
Postconditions: x.get_­id() == id() and get_­id() returns the value of x.get_­id() prior to the assignment.
Returns: *this.

32.4.3.6 Members [thread.thread.member]

void swap(thread& x) noexcept;
Effects: Swaps the state of *this and x.
bool joinable() const noexcept;
Returns: get_­id() != id().
void join();
Effects: Blocks until the thread represented by *this has completed.
Synchronization: The completion of the thread represented by *this synchronizes with ([intro.multithread]) the corresponding successful join() return.
[Note 1:
Operations on *this are not synchronized.
— end note]
Postconditions: The thread represented by *this has completed.
get_­id() == id().
Throws: system_­error when an exception is required ([thread.req.exception]).
Error conditions:
  • resource_­deadlock_­would_­occur — if deadlock is detected or get_­id() == this_­thread​::​​get_­id().
  • no_­such_­process — if the thread is not valid.
  • invalid_­argument — if the thread is not joinable.
void detach();
Effects: The thread represented by *this continues execution without the calling thread blocking.
When detach() returns, *this no longer represents the possibly continuing thread of execution.
When the thread previously represented by *this ends execution, the implementation releases any owned resources.
Postconditions: get_­id() == id().
Throws: system_­error when an exception is required ([thread.req.exception]).
Error conditions:
  • no_­such_­process — if the thread is not valid.
  • invalid_­argument — if the thread is not joinable.
id get_id() const noexcept;
Returns: A default constructed id object if *this does not represent a thread, otherwise this_­thread​::​get_­id() for the thread of execution represented by *this.

32.4.3.7 Static members [thread.thread.static]

unsigned hardware_concurrency() noexcept;
Returns: The number of hardware thread contexts.
[Note 1:
This value should only be considered to be a hint.
— end note]
If this value is not computable or well-defined, an implementation should return 0.

32.4.3.8 Specialized algorithms [thread.thread.algorithm]

void swap(thread& x, thread& y) noexcept;
Effects: As if by x.swap(y).

32.4.4 Class jthread [thread.jthread.class]

32.4.4.1 General [thread.jthread.class.general]

The class jthread provides a mechanism to create a new thread of execution.
The functionality is the same as for class thread ([thread.thread.class]) with the additional abilities to provide a stop_­token ([thread.stoptoken]) to the new thread of execution, make stop requests, and automatically join.
namespace std { class jthread { public: // types using id = thread::id; using native_handle_type = thread::native_handle_type; // [thread.jthread.cons], constructors, move, and assignment jthread() noexcept; template<class F, class... Args> explicit jthread(F&& f, Args&&... args); ~jthread(); jthread(const jthread&) = delete; jthread(jthread&&) noexcept; jthread& operator=(const jthread&) = delete; jthread& operator=(jthread&&) noexcept; // [thread.jthread.mem], members void swap(jthread&) noexcept; [[nodiscard]] bool joinable() const noexcept; void join(); void detach(); [[nodiscard]] id get_id() const noexcept; [[nodiscard]] native_handle_type native_handle(); // see [thread.req.native] // [thread.jthread.stop], stop token handling [[nodiscard]] stop_source get_stop_source() noexcept; [[nodiscard]] stop_token get_stop_token() const noexcept; bool request_stop() noexcept; // [thread.jthread.special], specialized algorithms friend void swap(jthread& lhs, jthread& rhs) noexcept; // [thread.jthread.static], static members [[nodiscard]] static unsigned int hardware_concurrency() noexcept; private: stop_source ssource; // exposition only }; }

32.4.4.2 Constructors, move, and assignment [thread.jthread.cons]

jthread() noexcept;
Effects: Constructs a jthread object that does not represent a thread of execution.
Postconditions: get_­id() == id() is true and ssource.stop_­possible() is false.
template<class F, class... Args> explicit jthread(F&& f, Args&&... args);
Constraints: remove_­cvref_­t<F> is not the same type as jthread.
Mandates: The following are all true:
  • is_­constructible_­v<decay_­t<F>, F>,
  • (is_­constructible_­v<decay_­t<Args>, Args> && ...),
  • is_­move_­constructible_­v<decay_­t<F>>,
  • (is_­move_­constructible_­v<decay_­t<Args>> && ...), and
  • is_­invocable_­v<decay_­t<F>, decay_­t<Args>...> ||
    is_­invocable_­v<decay_­t<F>, stop_­token, decay_­t<Args>...>.
Preconditions: decay_­t<F> and each type in decay_­t<Args> meet the Cpp17MoveConstructible requirements.
Effects: Initializes ssource.
The new thread of execution executes invoke(decay-copy(std::forward<F>(f)), get_stop_token(), decay-copy(std::forward<Args>(args))...) if that expression is well-formed, otherwise invoke(decay-copy(std::forward<F>(f)), decay-copy(std::forward<Args>(args))...) with the calls to decay-copy being evaluated in the constructing thread.
Any return value from this invocation is ignored.
[Note 1:
This implies that any exceptions not thrown from the invocation of the copy of f will be thrown in the constructing thread, not the new thread.
— end note]
If the invoke expression exits via an exception, terminate is called.
Synchronization: The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.
Postconditions: get_­id() != id() is true and ssource.stop_­possible() is true and *this represents the newly started thread.
[Note 2:
The calling thread can make a stop request only once, because it cannot replace this stop token.
— end note]
Throws: system_­error if unable to start the new thread.
Error conditions:
  • resource_­unavailable_­try_­again — the system lacked the necessary resources to create another thread, or the system-imposed limit on the number of threads in a process would be exceeded.
jthread(jthread&& x) noexcept;
Postconditions: x.get_­id() == id() and get_­id() returns the value of x.get_­id() prior to the start of construction.
ssource has the value of x.ssource prior to the start of construction and x.ssource.stop_­possible() is false.
~jthread();
Effects: If joinable() is true, calls request_­stop() and then join().
[Note 3:
Operations on *this are not synchronized.
— end note]
jthread& operator=(jthread&& x) noexcept;
Effects: If joinable() is true, calls request_­stop() and then join().
Assigns the state of x to *this and sets x to a default constructed state.
Postconditions: x.get_­id() == id() and get_­id() returns the value of x.get_­id() prior to the assignment.
ssource has the value of x.ssource prior to the assignment and x.ssource.stop_­possible() is false.
Returns: *this.

32.4.4.3 Members [thread.jthread.mem]

void swap(jthread& x) noexcept;
Effects: Exchanges the values of *this and x.
[[nodiscard]] bool joinable() const noexcept;
Returns: get_­id() != id().
void join();
Effects: Blocks until the thread represented by *this has completed.
Synchronization: The completion of the thread represented by *this synchronizes with ([intro.multithread]) the corresponding successful join() return.
[Note 1:
Operations on *this are not synchronized.
— end note]
Postconditions: The thread represented by *this has completed.
get_­id() == id().
Throws: system_­error when an exception is required ([thread.req.exception]).
Error conditions:
  • resource_­deadlock_­would_­occur — if deadlock is detected or get_­id() == this_­thread​::​​get_­id().
  • no_­such_­process — if the thread is not valid.
  • invalid_­argument — if the thread is not joinable.
void detach();
Effects: The thread represented by *this continues execution without the calling thread blocking.
When detach() returns, *this no longer represents the possibly continuing thread of execution.
When the thread previously represented by *this ends execution, the implementation releases any owned resources.
Postconditions: get_­id() == id().
Throws: system_­error when an exception is required ([thread.req.exception]).
Error conditions:
  • no_­such_­process — if the thread is not valid.
  • invalid_­argument — if the thread is not joinable.
id get_id() const noexcept;
Returns: A default constructed id object if *this does not represent a thread, otherwise this_­thread​::​get_­id() for the thread of execution represented by *this.

32.4.4.4 Stop token handling [thread.jthread.stop]

[[nodiscard]] stop_source get_stop_source() noexcept;
Effects: Equivalent to: return ssource;
[[nodiscard]] stop_token get_stop_token() const noexcept;
Effects: Equivalent to: return ssource.get_­token();
bool request_stop() noexcept;
Effects: Equivalent to: return ssource.request_­stop();

32.4.4.5 Specialized algorithms [thread.jthread.special]

friend void swap(jthread& x, jthread& y) noexcept;
Effects: Equivalent to: x.swap(y).

32.4.4.6 Static members [thread.jthread.static]

[[nodiscard]] static unsigned int hardware_concurrency() noexcept;
Returns: thread​::​hardware_­concurrency().

32.4.5 Namespace this_­thread [thread.thread.this]

namespace std::this_thread { thread::id get_id() noexcept; void yield() noexcept; template<class Clock, class Duration> void sleep_until(const chrono::time_point<Clock, Duration>& abs_time); template<class Rep, class Period> void sleep_for(const chrono::duration<Rep, Period>& rel_time); }
thread::id this_thread::get_id() noexcept;
Returns: An object of type thread​::​id that uniquely identifies the current thread of execution.
No other thread of execution has this id and this thread of execution always has this id.
The object returned does not compare equal to a default constructed thread​::​id.
void this_thread::yield() noexcept;
Effects: Offers the implementation the opportunity to reschedule.
Synchronization: None.
template<class Clock, class Duration> void sleep_until(const chrono::time_point<Clock, Duration>& abs_time);
Effects: Blocks the calling thread for the absolute timeout ([thread.req.timing]) specified by abs_­time.
Synchronization: None.
Throws: Timeout-related exceptions ([thread.req.timing]).
template<class Rep, class Period> void sleep_for(const chrono::duration<Rep, Period>& rel_time);
Effects: Blocks the calling thread for the relative timeout ([thread.req.timing]) specified by rel_­time.
Synchronization: None.
Throws: Timeout-related exceptions ([thread.req.timing]).