I'm confused how std::jthread::get_stop_token
is designed to work, because it seems to have an inherent race condition.
Namely, the executing thread can't simply call std::jthread
on itself (as in this example) because it has no guarantee that the std::jthread
object is actually constructed by the time that it begins executing. It seem to me that for a thread to use its own get_stop_token
, it requires (at the very least) an extra event (like std::latch
) solely to synchronize against its own construction.
However, I do not see any examples or mentions of this issue online, and so it seems to me that this may not be the intended usage. It does seem rather clunky and error-prone, as well as potentially inefficient as it requires the worker thread to block on the main thread before proceeding.
So how is get_stop_token
supposed to be used?
Is there a simple example of the proper, intended usage of std::jthread::get_stop_token()
?
jthread
object is too guaranteed to be fully constructed by the time the thread function begins executing: "[thread.jthread.cons]/7 Synchronization: The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy off
." – Rebecarebecca