简体   繁体   English

使用std :: mutex发布并获取

[英]Release and Acquire with std::mutex

This is a question about the C++ standard. 这是一个关于C ++标准的问题。 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. 如果我误解了它是如何工作的,请随时纠正我。

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; 我使用std::mutex myMutex;保护对它们的访问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. 我知道你通常应该使用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();

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. 我的理解是,为了使它在线程之间可靠地工作,线程1必须在设置字符串后执行Release操作,并且两个必须在读取字符串之前执行Acquire

Reading the draft standard for C++11 I can't see anything that states that std::mutex does this, although it's fairly obvious that it's expected to or the mutex would be useless for anything. 阅读C ++ 11的标准草案我看不出任何说明std::mutex这样做的东西,虽然很明显它是预期的,或者互斥体对任何东西都没用。

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, 根据30.4.1.2p11,

Synchronization : Prior unlock() operations on the same object shall synchronize with (1.10) [ m.lock() ]. 同步 :对同一对象的先前unlock()操作应与(1.10)[ m.lock() ]同步。

Under 1.10p5, 低于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 . 非正式地,对A执行释放操作会强制对其他存储器位置的先​​前副作用变得对其他线程可见,这些线程稍后在A上执行消耗或获取操作。 [...] [...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM