是否需要内存屏障

是否需要内存屏障

本文介绍了如果第二个线程等待第一个线程终止,是否需要内存屏障?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设线程Alpha在不锁定的情况下正在写入变量A.第二个线程Beta正在等待Alpha终止,然后依次读取变量A.

Suppose that thread Alpha is writing to variable A without locking. A second thread Beta is waiting for Alpha to terminate, then reads the variable A in turn.

A的内容是否可能不是新鲜的?可以将内存写入延迟到线程生存期之后吗?等待线程Alpha终止的标准机制是否会隐式地充当内存屏障?

Is it possible that the contents of A will not be fresh? Can memory writes be delayed beyond the thread lifetime? Won't the standard mechanism of waiting for thread Alpha termination implicitly work as a memory barrier?

更新1

有没有没有记忆障碍的等待示例?

Are there any examples of waiting which does not include a memory barrier?

推荐答案

几乎可以肯定(用于等待线程终止的API需要出于自身目的使用内存屏障),但是我想为您提供一个明确的答案需要谈论所使用的特定线程API.

Almost certainly (the API used to wait for thread termination would need to use memory barriers for its own purposes), but I think for a definitive answer you'll need to talk about the specific threading API being used.

例如,posix为pthread_join()提供了这样的保证: https://stackoverflow.com/a/3208140/12711

For example, posix makes such a guarantee for pthread_join(): https://stackoverflow.com/a/3208140/12711

并且Win32文档证明,它是等待对象(例如,线程句柄)的同步API施加了内存障碍: http://msdn.microsoft.com/en-us/library/ms686355.aspx

And Win32 documents that it's synchronization APIs to wait on an object (for example, a thread handle) impose memory barriers: http://msdn.microsoft.com/en-us/library/ms686355.aspx

这篇关于如果第二个线程等待第一个线程终止,是否需要内存屏障?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:48