gpt4 book ai didi

c++ - 操作顺序是线程安全的吗?

转载 作者:行者123 更新时间:2023-12-01 14:20:08 24 4
gpt4 key购买 nike

我有一个 std::vector 用于将消息传递给线程。 vector 受互斥量保护:

vector<int> messages;
std::mutex m;

void postmessage (int msg) {
{
std::unique_lock Lock (m);
messages.push_back (msg);
}
}

当线程被唤醒时,它会像这样抓取整个消息队列:

  const auto my_messages = [this] {
std::unique_lock Lock (m);
return move (messages);
} ();

然后它处理 my_messages。问题:

  1. 这是否保证让 vector 处于空状态?换句话说,这是构造函数 (7) 在 cppreference 上的应用吗?保证 vector 为空?

  2. messages 上的操作是否保证在互斥量解锁之前完成?换句话说,这是线程安全的吗?

最佳答案

  1. Is this guaranteed to leave the vector in an empty state?

是的,返回值是从messages移动构造的,therefore messages is empty正如您正确推断的那样。

这并不适用于所有标准库类型,所以要小心——一些容器将源置于“未指定但有效”的状态,这意味着只有在没有先决条件的情况下对源执行操作才是安全的。在这些情况下,您可以安全地clear() 源以确保它是空的; clear() 没有先决条件,容器为空。

  1. Are the operations on messages guaranteed to be completed before the mutex is unlocked? In other words, is this thread-safe?

是的,这是安全的。看来你最担心的是“抢”消息队列的代码。

这个问题的症结在于Lock销毁后是否使用messages。答案是否定的,没有用到。

Construction of the returned value must complete before any locals are destructed .为什么?因为你可能会使用本地来构造返回值!

std::vector<int> foo() {
std::vector<int> x;
return x;
}

x 在构造返回值或存在未定义行为之前不能被析构。

关于c++ - 操作顺序是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62901773/

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