问题
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