通过引用将参数传递到std :: thread函数是否安全? [英] Is it safe to pass arguments by reference into a std::thread function?

查看:68
本文介绍了通过引用将参数传递到std :: thread函数是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <thread>
#include <string>
#include <vector>
#include <chrono>

using namespace std;

void f(const vector<string>& coll)
{
    this_thread::sleep_for(1h);

    //
    // Is coll guaranteed to be valid before exiting this function?
    //
}

int main()
{
    {
        vector<string> coll(1024 * 1024 * 100);
        thread(f, coll).detach();
    }

    //
    // I know std::thread will copy arguments into itself by default, 
    // but I don't know whether these copied objects are still valid
    // after the std::thread object has been destroyed.
    //

    while (true);
}

通过引用将参数传递到std :: thread函数是否安全?

推荐答案

作为@ T.C.的注释,您没有传递对线程的引用,只是在线程中复制了向量:

As @T.C.'s comment, you're not passing reference to thread, you just make a copy of the vector in the thread:

thread(f, coll).detach(); // It's NOT pass by reference, but makes a copy.

如果您真的想通过引用传递,则应编写以下内容:

If you really want to pass by reference, you should write this:

thread(f, std::ref(coll)).detach(); // Use std::ref to pass by reference

然后,如果线程尝试访问向量,则代码将出现段错误,因为线程运行时,很可能已经破坏了向量(因为它超出了主程序的作用域).

Then the code will get segment fault if the thread tries to access the vector, since when the thread runs, it's very likely the vector is already destructed (because it went out of it's scope in the main program).

所以对你的问题:

通过引用将参数传递给 std :: thread 函数是否安全?

  • 如果您确定对象在线程运行期间仍然有效,则是安全的;
  • 如果对象被破坏,那是不安全的,并且会出现段错误.
  • 这篇关于通过引用将参数传递到std :: thread函数是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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