问题描述 投票:0回答:1

在您的代码中,您有:
std::atomic<int> turn(0);
int free = 0;

然后在工作中():
c++ c++11 race-condition compare-and-swap
1个回答
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); } } }


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.