jthread - DryPerspective/Cpp17_jthread GitHub Wiki

Jthread

Class dp::jthread represents a thread with an associated stop state which will, if joinable, request a stop and join on its own destruction. It follows the same interface as std::jthread which itself largely follows that of std::thread. When constructing a jthread, if the callable used is invocable with a stop token as its first parameter, and if that stop token is not provided as an argument, the jthread will implicitly pass its own stop token to the callable. If not, the jthread will maintain a stop state which is not associated with the callable it is executing.

Interface

joinable Returns whether the underlying thread is joinable.
get_id Returns the id associated with the thread.
hardware_concurrency Returns the number of hardware threads supported by the current implementation.
join Blocks the current thread until the jthread's thread finishes execution.NB: Calling join() does not issue a stop request.
detach Detaches the underlying thread from the jthread object, to run independently.NB: Also clears the jthread object's owned stop state.
swap Swaps two jthread instances. Does not throw. Both a member and free function are provided.
get_stop_source Returns a dp::stop_source associated with the stop state of the object.
get_stop_token Returns a dp::stop_token associated with the stop state of the object.
request_stop Issues a stop request via the underlying stop state of the object.

Sample code


int main(){

    //No stop token provided => uses the jthread's own internal stop state
    dp::jthread my_thread{[](dp::stop_token tok){
        while(!tok.stop_requested()){
            do_some_thing();
        }
     }};

    //...

} //Here the destruction of my_thread implicitly issues a stop request and joins