大概是这样子的,
先申请一个数组,然后数组用作线程的同步变量。
然而同步变量却没有,然后之前能避开这个bug,是因为单独这个变量做了引用处理。
#include <iostream> #include <thread> using namespace std; void Test(int threadId, bool& b) { b = true; cout << threadId << "," << b; } int main() { bool b[4]; bool b0, b1, b2, b3; b0 = false; b1 = false; b2 = false; b3 = false; int a[4]; for (int i = 0; i < 4; i++) { a[i] = i; b[i] = false; std::thread th0([&]()->void { Test(i, b[a[i]]); }); th0.detach(); } while (true) { for (int i = 0; i < 4; i++) { cout << a[i] ; } cout << endl; for (int i = 0; i < 4; i++) { string str = b[i] ? "true" : "false"; cout << str << std::endl; } } return 0; }