Multithreading – thread:: join() prevents it from
•
Java
To learn how to use atomics in C 11, I tried the following code snippet:
#include <iostream> #include <thread> #include <atomic> using namespace std; struct solution { atomic<bool> alive_; thread thread_; solution() : thread_([this] { alive_ = true; while (alive_); }) { } ~solution() { alive_ = false; thread_.join(); } }; int main() { constexpr int N = 1; // or 2 for (int i = 0; i < N; ++i) { solution s; } cout << "done" << endl; }
If n equals 1, the output is complete However, if I set it to 2, the main thread will block in thread:: join() When n > Why do you think we can't see 1?
Note: if I use the following constructor:
solution() : alive_(true),thread_([this] { while (alive_); }) { }
It prints any value of n
Solution
If you do not initialize alive_ And set it only when the thread starts, you can perform the following interleaving execution:
MAIN: s::solution() MAIN: s.thread_(/*your args*/) MAIN: schedule(s.thread_) to run thread: waiting to start MAIN: s::~solution() MAIN: s.alive_ = false thread: alive_ = true MAIN: s.thread_.join() thread: while(alive_) {}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码