我是否需要内存屏障来访问由完成的线程修改的内存? [英] Do I need memory barrier for accessing memory modified by the thread that finished?

查看:82
本文介绍了我是否需要内存屏障来访问由完成的线程修改的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[此后,C ++术语]

我有一个线程A和线程B共享对整数值P的访问.线程A初始化该值并在运行时更新它.然后线程A完成.线程B等待线程A完成(标准OS API调用,无论使用哪种操作系统),并希望读取P.

线程B是否需要一个内存屏障来读取由线程A设置的最后一个连贯的P值?当OS API说线程A完成"时,它修改的内存更改是否可能对其他线程不可见?

请注意,这里只有线程在其中写入值,这可能会也可能不会与"

[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...

推荐答案

join与调用join的线程同步.也就是说,当B调用A.join()时,A进行的所有写操作对于B都是可见的.

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().

您可以认为这是A在完成std::atomic_thread_fence(memory_order_release)时执行的,而BA加入时执行std::atomic_thread_fence(std::memory_order_acquire的情况.

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.

线程B是否需要内存屏障

Does thread B need a memory barrier

是的,但是它们隐含在join中,您不必编写它们.

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

当OS API说线程A完成"时,它修改的内存更改是否可能对其他线程不可见?

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_variablestd::atomic_thread_fence(std::memory_order_acquire);

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);

这篇关于我是否需要内存屏障来访问由完成的线程修改的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆