简体   繁体   English

为什么人们使用原子交换而不是存储?

[英]Why do people use atomic exchange instead of store?

That is C++即C++

atomic_int turn(0)

turn.exchange(1);
turn.store(1);

this two code works same way, right?这两个代码的工作方式相同,对吧? But I checked many examples about lock use 1st one.但是我检查了很多关于锁使用第一个的例子。

Why?为什么?

Both statements store a value into the atomic variable.这两个语句都将值存储到原子变量中。 The exchange call returns the previously held value, which, in this case, is discarded. exchange调用返回先前持有的值,在本例中,该值被丢弃。 However, this does not mean the two calls are exactly the same.但是,这并不意味着这两个调用完全相同。 The exchange operation is a read-modify-write operation, while the store operation is only a write. exchange操作是一个读-修改-写操作,而store操作只是一个写操作。 That means that if we have:这意味着如果我们有:

// thread 1
turn.store(0);  // A

// thread 2
turn.exchange(1);  // B

and if thread 2 reads the value stored by thread 1, then line A synchronizes with line B. If thread 2 were to use store rather than exchange , there would be no such synchronization.如果线程 2 读取线程 1 存储的值,则 A 行与 B 行同步。如果线程 2 使用store而不是exchange ,则不会有这种同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM