Difference between boost::thread and std::thread

Difference between boost::thread and std::thread

本文关键字:thread and std Difference boost between      更新时间:2023-10-16

我有一个使用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::threadstd::bind都无法确定run的哪个重载,从而导致编译错误。

但是,如果您使用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::bindstd::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));
}