【问题标题】:cannot pass by reference to thread不能通过引用来传递线程
【发布时间】:2017-08-14 02:42:59
【问题描述】:

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

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

有人知道我能做什么吗?

【问题讨论】:

  • worker_routine 的签名是什么?
  • [Off Topic] 在使用 std::thread 时,您真的不需要将任何内容投射到 void*。它旨在与类型系统一起使用。
  • 您能尝试创建一个Minimal, Complete, and Verifiable Example 并展示给我们看吗?包括(至少)worker_routine 和 trained_images 的声明。

标签: c++ multithreading zeromq


【解决方案1】:

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

解决方案是使用 std::ref 之类的包装对象作为引用:

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

【讨论】:

    猜你喜欢
    • 2020-05-03
    • 2013-06-17
    • 1970-01-01
    • 2011-09-16
    • 2015-03-12
    • 2017-06-28
    • 1970-01-01
    • 2013-11-29
    • 2013-12-19
    相关资源
    最近更新 更多