发布和获取std :: mutex [英] Release and Acquire with std::mutex

查看:171
本文介绍了发布和获取std :: mutex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于C ++标准的问题。我只能访问草案标准,所以如果这是不同的官方,我道歉。如果我误解了这是如何工作,请随时更正我。

This is a question about the C++ standard. I only have access to the draft standard so if this is different in the official one, I apologise. Also if I've misunderstood how this works please feel free to correct me.

假设我有两个线程,一个写一个字符串和一个内容的副本的字符串。我保护访问他们使用 std :: mutex myMutex;
我知道你应该一般使用RAII类的锁,我只是使用锁

Assume I have two threads, one writing to a string and one making a copy of the contents of that string. I protect access to them using a std::mutex myMutex; I know you should in general use the RAII classes for locks, I just used lock and unlock explicitly to make the example more explicit.

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

我的理解是,为了在线程之间可靠地工作,线程必须执行

My understanding is that in order for this to work reliably between threads, thread one must perform a Release operation after setting the string, and thead two must perform an Acquire before reading the string.

读取草稿标准。

有人可以指点我的相关部分来看看吗?标准中的措词对于一位休闲读者来说往往不够清楚:)

Can someone point me to the relevent section to look at? The wording in the standard is often not exactly clear to a casual reader :)

推荐答案

Per 30.4.1.2p11,

Per 30.4.1.2p11,

同步:对同一对象执行之前的 unlock()应与(1.10)[ m.lock()]同步。

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

在1.10p5下,


[...]例如,获取互斥体的调用将执行获取操作
on所述位置包括互斥体。相应地,释放相同互斥体的调用将对这些相同的位置执行释放操作。非正式地,在 A上执行发布操作强制在其他存储器位置上的先前副作用变得对稍后在 A 上执行消费或获取操作的其他线程可见。 [...]

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

这篇关于发布和获取std :: mutex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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