r/cpp • u/vgasparyan • Aug 27 '19
A new thread in C++20 (jthread)
https://link.medium.com/GXKUz0GruZ18
u/Feminintendo Aug 27 '19
Of course, we could have achieved this with an atomic boolean...
Ok, I'll volunteer to be the idiot. Why does the boolean have to be atomic? Any writer is only ever going to set it to the same value, requested_stop, so there isn't an issue if two threads attempt to write at the same time. Readers don't need atomic access to read. And if you read in the middle of a write, who cares? You get the updated value the next time the thread polls it.
28
u/Xirema Aug 27 '19
It's undefined behavior. An optimizing compiler could decide that the boolean value, which never changes during the execution of a single thread, doesn't need to be read from every single time it's accessed. So for example:
bool stop = false; void loop() { while(!stop) { std::cout << "Can't stop won't stop." << std::endl; } }When a compiler looks at this, it's allowed to observe that inside the loop,
stopwill never change; therefore, it's perfectly valid to recompile the code to look like this:bool stop = false; void loop() { bool local_stop = stop; while(!local_stop) { std::cout << "Can't stop won't stop." << std::endl; } }Not every compiler will do this (MSVC for example won't) but some might, and thus we cannot rely on this code to behave the way we want.
Writing this, instead, guarantees correct behavior.
std::atomic_bool stop = false; void loop() { while(!stop) { std::cout << "Can't stop won't stop." << std::endl; } }Note that while it might be valid on your platform to instead use
volatile bool stop = false;, it's worth noting that this is also not standard compliant, because some CPU architectures behave badly when you try to concurrently write to a value in memory. In most situations (i.e. x86) it'll "work", but it's still not behavior you should rely on.6
u/orizh Aug 27 '19
To add that this is not just a theory but a reality, I have actually experienced exactly this in production. You should expect the compiler *will* optimize the flag away. It was not a fun bug to track down, especially since we were forced to use `volatile` as the platform did not have `std::atomic` implemented yet. Lucky that it worked without having to resort to asm.
2
u/TheMania Aug 28 '19
Word of warning: if your compiler is performing this optimization, you really should be using:
asm volatile("":::"memory");Just below any stores to the flag, and above any reads.
Aka, a memory barrier.
Without one it's only a matter of time until other problems present - as the compiler is free to (and will) reorder reads/writes of non-volatile variables around volatile variables as much as it likes, making them unsuitable for virtually any kind of thread synchronization on their own.
0
Aug 28 '19
[deleted]
2
u/orizh Aug 28 '19
It was a very old toolchain for NIOS II. There might have been platform specific atomics provided somewhere but I was young and did not know how to be a competent dev (tho neither did the senior devs!)
1
1
u/meneldal2 Aug 28 '19
some CPU architectures behave badly when you try to concurrently write to a value in memory
Afaik there's only a single write, so there should be no contention.
0
u/Ameisen vemips, avr, rendering, systems Aug 27 '19
In this situation, where the boolean defaults to
falseand is only ever set totrue, I cannot think of an architecture wherevolatilewould not suffice.13
u/HotlLava Aug 27 '19
Data races are undefined behaviour, so you can not allow them to happen in your code even if you think they are "benign".
Although in this case you could
std::memory_order_relaxedfor the loads/stores, because the sequencing doesn't really matter due to the reasons you describe.4
u/lewissbaker Aug 28 '19
The key thing that stop_token gives you that an atomic bool doesn’t is the ability to register a callback that will be invoked if someone call request_stop(). The stop_callback class template provides you the anility to register a callback for the duration of some scope.
This is key for implementing cancellation of async operations, but can also be used to implement an interruptible blocking wait (see stop_token overloads of condition_variable_any wait functions) or an interruptible sleep (eg using the new binary_semaphore).
3
u/gmrple Aug 28 '19
It is never OK to read something possibly modified in a different thread without synchronization. What level of synchronization is needed depends on what you are actually reading. For primitive types, you should have a look at atomic reads, e.g. in the form of std::atomic<bool>.
The reason synchronization is always needed is that the processors will have the data possibly shared in a cache line. It has no reason to update this value to a value possibly changed in a different thread if there is no synchronization. Worse, yet, if there is no synchronization it may write the wrong value if something stored close to the value is changed and synchronized.
Dietmar Kühl https://stackoverflow.com/a/9201088/8039122
2
10
u/rdtsc Aug 27 '19
What's with the naming? jthread almost looks like thread, why not something readable like joining_thread? And don't get me started on stop_token…
12
u/sumo952 Aug 27 '19
> `jthread`
I have to immediately think about Java here. Not sure why, I've last programmed Java many, many years ago.
2
u/HappyFruitTree Aug 29 '19
I also think about Java. All the Swing classes, used for building GUIs in Java, seem to start with J.
JFrame, JButton, JLabel, JTextArea, etc.
3
Aug 27 '19
Does it provide the ability to wait on the stop_token with a timeout? I presently pass windows events to all my threads which can be both tested for stop but also waited on allowing the thread to sleep but wake and exit if stopped.
5
u/lewissbaker Aug 28 '19
The only usage of stop_token in the standard library in C++20 is in std::jthread as the source of a request to stop and in std::condition_variable_any, where you can pass a stop_token to some new overloads of the wait() function.
However, I expect in time there will be the addition of many more overloads of functions that take stop_token. std::this_thread::sleep_for() seems like a likely candidate.
In C++20 you can write an efficient interruptible sleep using binary_semaphore and stop_callback.
template<typename Rep, typename Ratio> void sleep_for(std::chrono::duration<Rep,Ratio> d, std::stop_token st) { std::binary_semaphore sem{0}; std::stop_callback cb{st, [&] { sem.release(); }}; sem.try_acquire_for(d); }
9
u/khleedril Aug 27 '19 edited Aug 27 '19
This all seems like so little to me that it's not worth bothering to put it in the standard, and if anything is an ode to lazyness. The current thread model forces you to think about and make a decision over detach or join (or leak, which unfortunately is the default with std::thread), atomic booleans are a clean way to signal requested stop, and anyway threads must under all circumstances be engineered by the coder so that stopping is well defined.
All I would ask for is that the standard introduces std::detached_thread and std::joinable_thread (or maybe functions std::make_detached_thread and std::make_joinable_thread) which are just like std::thread except for different default behaviour. The std::thread can then be deprecated in C++23, and all the constructors made private in C++26 :)
17
u/Kronephon Aug 27 '19
This all seems like so little to me that it's not worth bothering to put it in the standard, and if anything is an ode to lazyness.
This line of thinking is applicable to lot of features added (especially since C++11). In truth "lazyness" makes for quicker coding and the end programmer might not need to think about implementation (same as he doesn't on many C++ std features). There is always the option for a more detailed approach but your every approach shouldn't have to be detailed and laborious.
1
1
u/serendipitybot Aug 28 '19
This submission has been randomly featured in /r/serendipity, a bot-driven subreddit discovery engine. More here: /r/Serendipity/comments/cwefds/a_new_thread_in_c20_jthread_xpost_from_rcpp/
-1
u/axilmar Aug 27 '19
The only reason we have cooperatively stopping threads is because operating systems have not provided a solution for terminating a thread gracefully.
Upon issuing a thread stop, operating systems could have simply set a thread to execute an exit function when they are activated.
The exit function could then throw an exception in C++, which would unwind the stack gracefully.
23
u/CptCap -pedantic -Wall -Wextra Aug 27 '19 edited Aug 27 '19
the exit function could then throw an exception in C++
No, this would be really really bad.
If a thread gets interrupted while inside a
noexceptfunction, it'll terminate the program. This also breaks all theis_nothrow_xxxtraits as well as all the code that use them, in ways that are hard if not impossible to predict.7
15
u/HappyFruitTree Aug 27 '19
Wouldn't that mean the code could throw from everywhere?
1
u/axilmar Aug 27 '19
Yes.
9
u/HappyFruitTree Aug 27 '19
Sounds like writing exception-safe code would suddenly become much more difficult.
3
u/axilmar Aug 27 '19
I never understood why exception-safe code is needed, to tell you the truth.
10
u/HappyFruitTree Aug 27 '19 edited Aug 27 '19
Well, if you don't care whether the program is well-behaved when an exception is thrown I don't see why you proposed throwing an exception in the first place. Wouldn't it have been easier to just terminate the thread without unwinding the stack?
Edit: I don't mean you need to provide strong exception safety guarantees but at least you shouldn't leak any resources or trigger undefined behaviour when an exception is thrown.
2
u/axilmar Aug 27 '19
RAII safety is absolutely needed, I never understood why code that guarantees no exceptions are thrown is useful.
4
u/OldWolf2 Aug 27 '19
Resizing a vector is a common example.
Reallocating to increase the size of the memory block may involve having to move all of the current contents to the new block.
If the move constructor can throw an exception then that would leave the original vector with a bunch of husks , which is a no-no.
So the behavior is that if move construction can throw, it uses copy construction instead to set up the new memory block and then destructs the old objects.
3
u/yehezkelshb Aug 27 '19
Because this is the only way you can implement copy assignment operator with strong exception safety (i.e. the old data doesn't go away if the new data couldn't be put there). I think Effective C++ has an item about it, but it nevertheless a good exercise to try.
3
u/HappyFruitTree Aug 27 '19 edited Aug 27 '19
I think we need at least some building blocks that cannot throw.
Consider the following move assignment operator for this UniqueIntPtr class (similar to std::unique_ptr<int>).
class UniqueIntPtr { public: // ... UniqueIntPtr& operator=(UniqueIntPtr&& other) { delete ptr; ptr = other.ptr; other.ptr = nullptr; return *this; } ~UniqueIntPtr() { delete ptr; } // ... private: int* ptr; };It doesn't throw any exceptions, so there is nothing that can go wrong.
Now, let's say an exception can be thrown between any two statements. Try to implement the move assignment operator in such a way that it never leaks or leads to undefined behaviour when an exception is thrown.
If you manage to do that, do the same but pretend an exception can be thrown between any two machine instructions (because I assume a context switch can happen between any two instructions ;) ).
I don't expect you to use try-catch blocks here because you don't want an exception to be thrown while you are handling another exception, do you? I don't really expect you to be able to do this at all. I expect you to try, fail, and hopefully realize something.
0
Aug 28 '19
[deleted]
1
u/markopolo82 embedded/iot/audio Aug 28 '19
Problems with it on iOS Reddit client? Me too!
I had to open in safari to be able to close the login window
52
u/TheThiefMaster C++latest fanatic (and game dev) Aug 27 '19
It's a pity this wasn't thought about when threads were first added - it seems to me that this would be a better fit for being
std::thread, with the current std::thread being better named something likeraw_thread- shorter names should be for safer functions, with longer names for less safe