gpt4 book ai didi

c++ - boost::thread 和 std::thread 之间的区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:11:50 26 4
gpt4 key购买 nike

我有一个使用 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 都不能确定 的哪个重载>运行是有意的,导致编译错误。

但是,如果您使用 boost::bind,这会起作用。所以我会使用并手动执行绑定(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 依赖可变参数模板参数,因此 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++ - boost::thread 和 std::thread 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13476201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com