Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Atomic Memory Order #3

Open
levy5307 opened this issue Mar 23, 2020 · 0 comments
Open

Atomic Memory Order #3

levy5307 opened this issue Mar 23, 2020 · 0 comments

Comments

@levy5307
Copy link
Owner

https://levy5307.github.io/blog/atomic-memory-order/

虽然是六种类型,但是理解了四种同步的情形基本就差不多了。

对于单线程来说,编译器会在不影响程序执行结果的前提下对原子语句顺序进行重排,同时有些弱序cpu(spark是弱序,但x86是强序)也会对指令执行顺序进行重排。但是这种重拍对于多线程来说可能就会造成问题。

Sequential consistency: 即对于所有的环境变量,代码在线程中运行的顺序与程序员看到的代码顺序一致。对于弱序cpu需要添加内存栅栏(mem fence)


Relaxed ordering: 不保证顺序,性能最高。有可能会由于编译器或者cpu的重排导致程序运行出问题。


Release – acquire: Release保证在其之前的(所有)语句一定会先与该Release语句执行, Acquire语句保证在其之后的(所有)语句一定会后语该语句执行。Release用于store,Acquire用于load。


Release – consume: 如果只想同步一个 x 的读写操作,结果把 release 之前的写操作都顺带同步了?如果想避免这个额外开销怎么办?用 release – consume。同步还是一样的同步,这回副作用弱了点:memory_order_cosume只保证原子操作发生在与其(memory_order_consume指定的)有关的原子操作之前,对于无关的操作则无法保证顺序。例如:

atomic<string*> ptr;
atomic data;

producer:

string *p = new string(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant