不能通过引用传递给线程 [英] cannot pass by reference to thread
问题描述
我试图通过引用传递一个线程,一个定义为的变量:
I am trying to pass by reference to a thread, a variable defined as:
zmq::context_t context(1);
像这样:
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...>)
如果我尝试使用它执行 std::ref()
,我会收到一个已删除的函数错误.
If I try to do std::ref()
with it, I get a deleted function error.
有人知道我能做什么吗?
Does anyone know what I can do?
推荐答案
问题似乎出在 trained_images
参数上,您的线程函数将其作为引用参数.这样做的问题是 std::thread
对象不能真正处理引用(它复制线程函数的参数,并且不能复制引用).
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).
解决方案是使用包装器对象,如 std::ref
供参考:
The solution is to use wrapper objects like std::ref
for references:
t[thread_nbr] = std::thread(worker_routine, &context, std::ref(trained_images));
这篇关于不能通过引用传递给线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!