加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – boost :: thread和std :: thread之间的区别

发布时间:2020-12-16 07:33:36 所属栏目:百科 来源:网络整理
导读:我有一个使用boost :: thread工作的地方(使用boost :: asio的例子) std::vectorboost::shared_ptrboost::thread threads; for (std::size_t i = 0; i io_services_.size(); ++i) { boost::shared_ptrboost::thread thread(new boost::thread( boost::bind(bo
我有一个使用boost :: thread工作的地方(使用boost :: asio的例子)

std::vector<boost::shared_ptr<boost::thread> > threads;
  for (std::size_t i = 0; i < io_services_.size(); ++i)
  {
    boost::shared_ptr<boost::thread> thread(new boost::thread(
          boost::bind(&boost::asio::io_service::run,io_services_[i])));
    threads.push_back(thread);
  }

如果我尝试使用它与std:thread我得到编译错误:

std::vector<std::thread> threads;
for (std::size_t i = 0; i < this->ioServices.size(); ++i)
{
    std::thread thread(&boost::asio::io_service::run,ioServices[i]); // compile error std::thread::thread : no overloaded function takes 2 arguments   

    threads.push_back(std::move(thread));
}

解决方法

理论上,两者都应该工作,因为std :: thread有一个vararg构造函数,它基本上调用它的参数,好像它与std :: bind一起使用.问题似乎是,至少在我的实现(gcc 4.6.3)中,std :: thread和std :: bind都无法确定运行的哪个重载,从而导致编译错误.

但是,如果你使用boost :: bind,这是有效的.所以我会使用,并手动手动执行绑定:

std::vector<std::thread> threads;
for (std::size_t i = 0; i < this->ioServices.size(); ++i)
{
    std::thread thread(boost::bind(&boost::asio::io_service::run,ioServices[i])); 

    threads.push_back(std::move(thread));
}

编辑:似乎boost :: bind成功,因为它有大量的重载,并且基于它提供的参数数量,在boost :: bind的重载解析和模板替换期间,它可以确定boost :: asio的哪个重载:: io_service :: run是有意的.

但是,由于std :: bind和std :: thread依赖于vararg tempalte参数,因此run的两个重载同样有效,并且编译器无法解析使用哪一个.这种模糊性导致无法确定您所看到的失败的结果.

另一个解决方案是:

std::vector<std::thread> threads;
typedef std::size_t (boost::asio::io_service::*signature_type)();
signature_type run_ptr = &boost::asio::io_service::run;

for (std::size_t i = 0; i < this->ioServices.size(); ++i)
{
    std::thread thread(run_ptr,ioServices[i]); 

    threads.push_back(std::move(thread));
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读