c++ - 使用 std::mutex 释放和获取

标签 c++ c++11 memory-barriers stdmutex

这是一个关于C++标准的问题。我只能访问标准草案,所以如果这与官方标准不同,我深表歉意。另外,如果我误解了它的工作原理,请随时纠正我。

假设我有两个线程,一个写入字符串,一个复制该字符串的内容。我使用 std::mutex myMutex; 保护对它们的访问 我知道您通常应该将 RAII 类用于锁,我只是明确地使用了锁定和解锁以使示例更加明确。

// Global variable
std::string message;
std::mutex myMutex;

// Thread one
myMutex.lock();
message = "Hello";
myMutex.unlock();

// Thread two
myMutex.lock();
std::string copy = message;
myMutex.unlock();

我的理解是,为了使其在线程之间可靠地工作,线程一必须在设置字符串后执行释放操作,线程二必须执行获取在读取字符串之前。

阅读 C++11 的标准草案我看不到任何声明 std::mutex 这样做的内容,尽管很明显它是预期的,或者互斥量对于任何东西。

有人可以指点我相关的部分看看吗?标准中的措辞对于不经意的读者来说通常不是很清楚 :)

最佳答案

根据 30.4.1.2p11,

Synchronization: Prior unlock() operations on the same object shall synchronize with (1.10) [m.lock()].

在 1.10p5 下,

[...] For example, a call that acquires a mutex will perform an acquire operation on the locations comprising the mutex. Correspondingly, a call that releases the same mutex will perform a release operation on those same locations. Informally, performing a release operation on A forces prior side effects on other memory locations to become visible to other threads that later perform a consume or an acquire operation on A. [...]

关于c++ - 使用 std::mutex 释放和获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13359582/

相关文章:

c++ - 我可以在 C++ 中实现自治的 `self` 成员类型吗?

c++ - glReadPixels depth_buffer_component 总是返回 1

c++ - 以编程方式读取 Internet Explorer cookie

c++ - 对静态 constexpr 字符串的 undefined reference (除非它是一个指针)

x86 - LFENCE 是否在 AMD 处理器上进行序列化?

c++ - GCC -fPIC 选项

c++ - 深度复制具有自引用指针的类

c++ - visual studio 2012 中的 initializer_list

java - Java中内存屏障的行为

linux - 自旋锁真的需要 DMB 吗?