Ben*_*ahi 3 multithreading atomic race-condition c++11
为了理解如何在C++ 11中使用原子,我试着遵循代码片段:
#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;
}
Run Code Online (Sandbox Code Playgroud)
如果N等于1,则输出为done.但是,如果我将其设置为2,主线程将阻塞在thread :: join().为什么你认为我们什么done时候看不到N> 1?
注意:如果我使用以下构造函数:
solution() : alive_(true), thread_([this] {
while (alive_);
}) { }
Run Code Online (Sandbox Code Playgroud)
它打印done任何N值.
如果您没有初始化alive_并且仅在线程启动时设置它,则可以执行以下交错执行:
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_) {}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |