单线程内存屏障 [英] Memory barrier in a single thread

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

问题描述

我有这个关于内存屏障的问题.

I have this question related to memory barriers.

在多线程应用程序中,如果数据在它们之间共享,则必须使用内存屏障,因为在一个内核上运行的线程中的写入可能不会被另一个内核上的另一个线程看到.

In a multi-threaded applications a memory barrier must be used if data is shared between them , because a write in a thread that is runing on one core , may not be seen by another thread on an another core.

根据我从其他关于内存屏障的解释中读到的内容,据说如果您有一个处理某些数据的单线程,则不需要内存屏障.

From what I read from other explanations of memory barriers, it was said that if you have a single thread working with some data you don't need a memory barrier.

这是我的问题:可能是一个线程修改了特定内核上的一些数据,然后在一段时间后调度程序决定将该线程迁移到另一个内核.

And here is my question: it could be the case that a thread modifies some data on a specific core, and then after some time the scheduler decides to migrate that thread to another core.

这个线程是否有可能看不到它在另一个内核上所做的修改?

Is it possible that this thread will not see its modifications done on the other core?

推荐答案

原则上:是的,如果程序执行从一个内核移动到下一个内核,它可能看不到前一个内核上发生的所有写操作.

In principle: Yes, if program execution moves from one core to the next, it might not see all writes that occurred on the previous core.

请记住,进程不会自行切换内核.操作系统抢占执行并将线程移动到新内核.因此,确保在执行上下文切换时正确同步内存操作也是操作系统的责任.

Keep in mind though that processes don't switch cores by themselves. It is the operating system that preempts execution and moves the thread to a new core. Thus it is also the operating system's responsibility to ensure that memory operations are properly synchronized when performing a context switch.

对于作为程序员的您来说,这意味着,只要您不是尝试在没有 SMP 感知操作系统的级别上工作(例如,当您尝试编写自己的操作系统或在嵌入式操作系统上工作时)没有成熟操作系统的平台),您无需担心这种情况下的同步问题.

For you as a programmer this means that, as long as you are not trying work on a level where there is no SMP-aware OS (for instance, when you are trying to write your own OS or when working on an embedded platform without a fully-fledged OS), you do not need to worry about synchronization issues for this case.

这篇关于单线程内存屏障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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