c++ - 线程安全和 std::move

标签 c++ lambda thread-safety move


前言: 当我输入新代码时,我会不假思索地将我的函数声明为 pass-by-reference-to-const,有时当我意识到时不得不返回并更改它这不是我想做的。

我正在编写一个无限期运行的工作线程类,并提供字符串(来自另一个线程)进行处理。当我意识到我已将该函数声明为pass-by-ref 时,我返回将其更改为pass-by-value,以确保线程安全。 p>

但是,由于我想尽可能提高速度和效率,所以我先停下来探索各种选择。我写了一个小测试例程 - 发现我对一些关键概念很模糊。


切中要点:我先写了下面没有注释行的测试代码:

// std::thread _thread(workthread, move(str)); // Thread safe (contents are moved)

因此,暂时忽略该行。

#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <atomic>

std::atomic<bool> done = false;

void workthread(const std::string &str)
{
    std::string &s = const_cast<std::string &>(str);
    s = "Work Thread"; // test to see if this changes the main thread's string
}

// This just watches for <enter> on the keyboard in order to quit the program.
void quitmonitor()
{
    std::getchar();
    done = true;
}

int main(int argc, char **argv)
{
    std::thread _monitor(quitmonitor);
    std::string str("Main Thread");

    std::thread _thread([&]{workthread(std::move(str));}); // Not thread safe (address is copied)
//  std::thread _thread(workthread, move(str));            // Thread safe (contents are moved)

    const auto minlen(str.length());
    const auto maxlen(minlen ? minlen*2 : 15);
    bool going_up = true;

    while (!done) {

        if (going_up)
            str.push_back('+');
        else
            str.pop_back();

        if (str.length() == minlen)
            going_up = true;
        if (str.length() == maxlen)
            going_up = false;

        std::cout << str << "\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    _thread.join();
    _monitor.join();
}

所有 main() 所做的就是创建一个字符串 "Main Thread",并将其 move 到线程函数 void workthread(const std::string & )。线程函数然后更改左值的数据并返回。 main 继续执行一个循环,该循环仅将其本地字符串打印到控制台(带有一些额外的视觉效果,以便于在屏幕上看到发生的事情)。这是输出:

function called with lambda

所以,它没有像我预期的那样工作。我原以为线程实例化会将str“move ”到线程函数(清空其进程中的数据),而线程对函数的字符串参数的赋值不会有任何影响。但显然确实如此,如输出所示。

这一定与我用 lambda 构造 _thread 的事实有关: std::thread _thread([&]{workthread(std::move(str));});//非线程安全(地址被复制)

然后我将实例化更改为: std::thread _thread(工作线程, move (str));//线程安全(内容被 move ) 它按预期工作: function called as bind

Q1:为什么这两个实例,lambda 与 bind(我猜?) 会产生不同的结果?

Q2:通过将其声明为传递引用,我实际上是在给自己买东西吗?

我应该指出,实际程序对时间要求很高,并且旨在在专用服务器上不间断地运行多年。我正在努力使软件的开销尽可能低,以确保它可以保持同步(与外部时钟),并且不会累积时间错误。

最佳答案

std::thread _thread([&]{workthread(std::move(str));});

创建 _thread 时,它会调用您的 lambda 函数,该函数会调用 workthread(std::move(str))。请注意,std::move 实际上并没有做任何事情;它只是对右值引用的转换。您永远不会从 str move ,您只是以迂回的方式将引用转换为 std::string& 并分配给它。

这也意味着您在 str 上存在数据竞争,因为您在主线程和 _thread 之间的访问是不同步的。


不过,这段代码是从字符串中移出的:

std::thread _thread(workthread, move(str));

如果你看std::thread's constructor (它在该列表中是 (3)),您会看到它将参数“复制”到函数调用;它大致调用:

workthread(decay_copy(std::move(str)))

这个 decay_copy 实际上确实从字符串中 move ,因为它按值返回:

template <class T>
std::decay_t<T> decay_copy(T&& v) { return std::forward<T>(v); }

这就是为什么您看到 str 是从中移出的。但是,您的程序实际上依赖于未指定的行为,因为 - 在从 std::string move 之后 - 字符串处于“有效但未指定的状态”(std::stringmove constructormove assignment operator )。你不能指望 str 在被移出后是一个空字符串。

关于c++ - 线程安全和 std::move,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49204658/

相关文章:

Python:lambda 表达式的数据帧错误

sockets - golang net.UDPConn 和 net.TCPConn 线程安全吗??我可以在多线程中读取或写入单个 UDPConn 对象吗?

c# - 是否需要保护对 .net 集合的只读并发访问?

java - 我的类是否是线程安全的,有多个线程访问其变量?

C++ boost : Any gotchas with BOOST_FOREACH?

c++ - 常量变量初始化仅适用于成员初始化列表

数组中的 C++ CRTP

c++ - 有没有一种方便的方法可以让一些 Qt 小部件只输入一个字符?

java - 展平来自单例的流可选

node.js - AWS lambda 发送 SNS "succeeds"但消息并未实际发送