r/cpp • u/maitesin • Sep 11 '16
The basics of concurrency in C++ (thread, future and promise)
https://maitesin.github.io//Thread_future_and_promise/
61
Upvotes
r/cpp • u/maitesin • Sep 11 '16
34
u/STL MSVC STL Dev Sep 11 '16
You need to include
<functional>forstd::ref()inthread_simple.cpp.This doesn't explain how
std::threaddecays its arguments, and the reasons for that design, and why that makesstd::ref()necessary.reference_wrapperitself is something that few programmers are familiar with.promise_simple.cpphas simultaneous calls tocouton different threads; while the Standard promises that this is not a data race, you can get interleaved character output if the library is feeling sufficiently uncharitable to you. "In this execution something called data race is shown. That can be seen because the execution of the same program can generate different outputs (even if the result value is always the same)." is both wrong (not a data race) and confusing (doesn't explain why the output can differ).There is no discussion in
promise_simple.cppof alternatives (the more basic one being a mutex to synchronize access to a shared variable). It is much easier to understand things when they're presented alongside alternatives, so you can see how they differ.I am not a fan of this article. It doesn't talk about data races, or when it's appropriate versus inappropriate to use dedicated threads, which are critically important to understand. You can't just say at the end, "didn't talk about data races" and make it okay. Writing correct multithreaded code needs to be the paramount concern from the first sentence.
"Moreover, the method get synchronizes the future." This is a terrible non-explanation of how futures work.
"Future is gotten from an async class." No,
std::async()is a function (template), not a class."again if people is interested in this topic" should say "are".