2014-12-08 31 views
2
bool expected = false; 
extern std::atomic<bool> current; // set somewhere else 
while (!current.compare_exchange_weak(expected, true) 
     && !expected); 

什么是使用此代码与current.exchange(expected)原子交换vs compare_exchange_xxx

exchange是否会诱发一些竞争条件?

编辑:同样的问题与current.store(expected)

+0

它可能取决于修改'current'的其他线程中发生了什么。他们在做什么? – 2014-12-08 09:04:41

+0

其实我的问题更多关于教育目的,如果别人线程做current.store或current.exchange有一些区别吗? – Guillaume07 2014-12-08 09:07:34

回答

0

exchangecompare_exchange_weak具有不同一般的语义,但在你的例子它看起来并不像你依靠这将证明,任何行为。如果你有两个或更多的线程竞相写入相同的值,谁先到达那里并不重要,事实上你甚至不需要std :: atomic的保护。要理解这些差异,你必须看一个例子,其中给定线程的行为取决于在到达exchangecompare_exchange_weak之前发生的事情。