cannot pass by reference to thread

好久不见. 提交于 2019-12-13 03:36:02

问题


I am trying to pass by reference to a thread, a variable defined as:

zmq::context_t context(1);

like this:

t[thread_nbr] = std::thread(worker_routine, (void *)&context, trained_images);

However, when I do I get the following error:

/usr/include/c++/5/functional:1505:61: error: no type named ‘type’ in ‘class std::result_of<void* (*(void*, std::vector<TrainedImage>))(void*, std::vector<TrainedImage>&)>’
   typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                         ^
/usr/include/c++/5/functional:1526:9: error: no type named ‘type’ in ‘class std::result_of<void* (*(void*, std::vector<TrainedImage>))(void*, std::vector<TrainedImage>&)>’
     _M_invoke(_Index_tuple<_Indices...>)

If I try to do std::ref() with it, I get a deleted function error.

Does anyone know what I can do?


回答1:


The problem seems to be the trained_images argument which your thread-function takes as argument by reference. The problem with this is that the std::thread object can't really handle references (it copies the arguments to the thread function, and references can't be copied).

The solution is to use wrapper objects like std::ref for references:

t[thread_nbr] = std::thread(worker_routine, &context, std::ref(trained_images));


来源:https://stackoverflow.com/questions/45390068/cannot-pass-by-reference-to-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!