gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:19 24 4
gpt4 key购买 nike

这是一个关于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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com