不能通过引用传递给线程

cannot pass by reference to thread

我试图通过引用传递给线程,变量定义为:

zmq::context_t context(1);

像这样:

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

但是,当我这样做时,出现以下错误:

/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(),我会收到删除函数错误。

有人知道我能做什么吗?

问题似乎是 trained_images 参数,您的线程函数通过引用将其作为参数。这样做的问题是 std::thread 对象无法真正处理引用(它 复制 线程函数的参数,并且不能复制引用)。

解决方案是使用像 std::ref 这样的包装器对象作为引用:

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