在您的代码中,您有:
std::atomic<int> turn(0);
int free = 0;
然后在工作中():
if(turn.compare_exchange_strong(free, pid)) { … }
线程都使用与预期值相同的变量,并且由于其通过compare_exchange_strong操作而修改了故障时的修改,free的值可能不再是您预期的(为0)。
EACH线程应将其自己的本地变量用作预期值。
void Work(int pid) {
while(true) {
int expected = 0; // local copy of free
if(turn.compare_exchange_strong(expected, pid)){
std::cout << "Thread " << pid << " is running on core " << sched_getcpu() << std::endl;
turn.store(0);
}
}
}