我是否需要内存屏障来访问由完成的线程修改的内存?
Do I need memory barrier for accessing memory modified by the thread that finished?
[以下为 C++ 术语]
我有一个线程 A 和线程 B,它们共享对整数值 P 的访问。线程 A 初始化这个值并在 运行 时更新它。然后线程 A 完成。线程 B 等待线程 A 完成(标准 OS API 调用,无论使用什么 OS)并想要读取 P。
线程 B 是否需要内存屏障来读取一致的、最后由线程 A 设置的 P 值?有没有可能当OSAPI说"thread A finished"时,它修改的内存变化对其他线程还不可见?
请注意,只有一个线程在此处写入值,这可能会或可能不会将此问题与之前提出的“”区分开来。我的直觉告诉我答案应该是一样的,但是...
join
与调用 join
的线程同步。也就是说,当 B
调用 A.join()
.
时,A
进行的所有写入都将对 B
可见
您可以将其视为 A
在完成时执行 std::atomic_thread_fence(memory_order_release)
并且 B
在 A
加入时执行 std::atomic_thread_fence(std::memory_order_acquire
。
Does thread B need a memory barrier
是的,但它们隐含在 join
中,您不必编写它们。
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?
除 join
的调用者以外的线程将需要额外的同步,例如std::condition_variable
或 std::atomic_thread_fence(std::memory_order_acquire);
[以下为 C++ 术语]
我有一个线程 A 和线程 B,它们共享对整数值 P 的访问。线程 A 初始化这个值并在 运行 时更新它。然后线程 A 完成。线程 B 等待线程 A 完成(标准 OS API 调用,无论使用什么 OS)并想要读取 P。
线程 B 是否需要内存屏障来读取一致的、最后由线程 A 设置的 P 值?有没有可能当OSAPI说"thread A finished"时,它修改的内存变化对其他线程还不可见?
请注意,只有一个线程在此处写入值,这可能会或可能不会将此问题与之前提出的“
join
与调用 join
的线程同步。也就是说,当 B
调用 A.join()
.
A
进行的所有写入都将对 B
可见
您可以将其视为 A
在完成时执行 std::atomic_thread_fence(memory_order_release)
并且 B
在 A
加入时执行 std::atomic_thread_fence(std::memory_order_acquire
。
Does thread B need a memory barrier
是的,但它们隐含在 join
中,您不必编写它们。
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?
除 join
的调用者以外的线程将需要额外的同步,例如std::condition_variable
或 std::atomic_thread_fence(std::memory_order_acquire);