Do I need memory barrier for accessing memory modified by the thread that finished?

非 Y 不嫁゛ 提交于 2019-12-24 00:54:35

问题


[Hereinafter, C++ terms]

I have a thread A and thread B that share access to the integer value P. Thread A initializes this value and updates it while running. Then thread A completes. Thread B waits for thread A to complete (standard OS API call, whatever OS is used) and wants to read P.

Does thread B need a memory barrier to read a coherent, last set by thread A, value of P? Is there a possibility that when OS API says "thread A finished", the changes of memory it modified are not visible to other threads yet?

Note that there only one thread writing the value here, which may or may not distinguish this question from "Is there an implicit memory barrier with synchronized-with relationship on thread::join?" asked before. My gut feeling tells me the answer should be the same, but...


回答1:


join synchronizes with the thread that calls join. That is, all writes that A makes will become visible to B when B calls A.join().

You can think of this as A executing std::atomic_thread_fence(memory_order_release) as it finishes and B executing std::atomic_thread_fence(std::memory_order_acquire as A joins.

Does thread B need a memory barrier

Yes, but they are implicit in join and you do not have to write them.

Is there a possibility that when OS API says "thread A finished", the changes of memory it modified are not visible to other threads yet?

Threads other than the caller of join will need additional synchronization, e.g. std::condition_variable or std::atomic_thread_fence(std::memory_order_acquire);



来源:https://stackoverflow.com/questions/43102138/do-i-need-memory-barrier-for-accessing-memory-modified-by-the-thread-that-finish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!