Difference between boost::thread and std::thread
Difference between boost::thread and std::thread
我有一个使用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
都无法确定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::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));
}
相关文章:
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 为什么 Clang 不允许"and"作为函数名称?
- 在std::thread中,joinable()然后join()线程安全吗
- 位阵列上的快速AND运算
- 是否可以在 C++03 中定义'move-and-swap idiom'等效项
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 分离一个静态常量 std::thread?
- 尝试使用 std::vector<std::thread时出现静态断言失败错误>
- 使用 thread 类在 C++ 中构造线程的动态数组时出错
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- BoostPython and CMake
- OpenSSL BIO and SSL_read
- std::thread and move in visual studio 2013
- Difference between boost::thread and std::thread
- Pantheios and boost::thread
- std::thread and std::mutex issue
- Using cvQueryFrame and boost::thread together
- MinGW and std::thread
- std::thread and std::cin.get