To understand how to use atomics in C++11, I tried to 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 done. However, if I set it to 2, the main thread blocks at thread::join(). Why do you think we don't see done when N > 1?
Note: If I use the following constructor:
solution() : alive_(true), thread_([this] {
while (alive_);
}) { }
it prints done for any value of N.
Aucun commentaire:
Enregistrer un commentaire