代码之家  ›  专栏  ›  技术社区  ›  Wais Kamal

如何传递一个引用线程的函数?复制

  •  0
  • Wais Kamal  · 技术社区  · 5 年前

    为什么在创建时不能通过引用传递对象 std::thread ?

    例如,下面的snippit给出了一个编译错误:

    #include <iostream>
    #include <thread>
    
    using namespace std;
    
    static void SimpleThread(int& a)  // compile error
    //static void SimpleThread(int a)     // OK
    {
        cout << __PRETTY_FUNCTION__ << ":" << a << endl;
    }
    
    int main()
    {
        int a = 6;
    
        auto thread1 = std::thread(SimpleThread, a);
    
        thread1.join();
        return 0;
    }
    

    错误

    In file included from /usr/include/c++/4.8/thread:39:0,
                     from ./std_thread_refs.cpp:5:
    /usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<void (*(int))(int&)>’:
    /usr/include/c++/4.8/thread:137:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(int&); _Args = {int&}]’
    ./std_thread_refs.cpp:19:47:   required from here
    /usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<void (*(int))(int&)>’
           typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                                 ^
    /usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<void (*(int))(int&)>’
             _M_invoke(_Index_tuple<_Indices...>)
             ^
    

    我已经改为传球了,但还有更好的方法吗?

    0 回复  |  直到 6 年前
        1
  •  131
  •   jfMR    8 年前

    使用显式初始化线程 reference_wrapper by using std::ref :

    auto thread1 = std::thread(SimpleThread, std::ref(a));
    

    或 std::cref 而不是 std::ref ,视情况而定)。根据来自的笔记 cppreference on std:thread :

    线程函数的参数是按值移动或复制的。如果引用参数需要传递给线程函数,则必须对其进行包装(例如 std::ref 或 标准::cref ).

        2
  •  34
  •   jfMR    8 年前

    基于 this comment ,这个答案详细阐述了论点没有通过的原因 通过参考 到线程函数 默认情况下 .

    考虑以下函数 SimpleThread() :

    void SimpleThread(int& i) {
        std::this_thread::sleep_for(std::chrono::seconds{1});
        i = 0;
    }
    

    现在,想象一下 会发生 如果编译了以下代码(确实 不 编写

    int main()
    {
        {
            int a;
            std::thread th(SimpleThread, a);
            th.detach();
        }
        // "a" is out of scope
        // at this point the thread may be still running
        // ...
    }
    

    论点 a 将被通过 通过参考 SimpleThread() 。线程可能仍在函数中休眠 SimpleThread() 在变量之后 一 已经超出范围,其生命周期已经结束。如果是, i 在里面 SimpleThread() 实际上是 悬挂参考 ,以及任务 i = 0 会导致 未定义行为 .

    通过使用类模板包装引用参数 std::reference_wrapper (使用函数模板 std::ref 和 std::cref )你明确表达了你的意图。

        3
  •  8
  •   Jarod42    5 年前

    std::thread 复制(/move)其参数,您甚至可能会看到注释:

    线程函数的参数是按值移动或复制的。如果引用参数需要传递给线程函数,则必须对其进行包装(例如,使用 std::ref 或 std::cref ).

    所以,你可以使用 std::reference_wrapper 通过 std::ref / std::cref :

    auto thread1 = std::thread(SimpleThread, std::ref(a));
    

    或者使用lambda:

    auto thread1 = std::thread([&a]() { SimpleThread(a); });
    
        4
  •  1
  •   Oleg Kokorin    5 年前

    不要路过 参考 如果您的对象是 基于堆栈 的调用中创建的新对象的指针 螺纹API .这样的对象将与线程一样长,但应在线程终止前显式删除。

    实例

    void main(){
    ...
    std::string nodeName = "name_assigned_to_thread";
    std::thread nodeThHandle = std::thread(threadNODE, new std::string(nodeName));
    ...
    }
    
    void threadNODE(std::string *nodeName){
    /* use nodeName everywhere but don't forget to delete it before the end */
    delete nodeName;
    }