2012-11-20 51 views
4

我在那里工作的事情使用提升的地方::线程差异::线程

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使用(使用boost :: ASIO为例):线程我得到编译错误:

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)); 
} 
+0

相关:http://stackoverflow.com/questions/10555566/is-there-any-difference-between-c11-stdbind-and-boostbind –

+0

你的编译错误不包含对'boost :: bind'的调用? – Chad

+0

@BartekBanachewicz更新了标题,因为这是关于boost :: tread和std :: thread之间的区别 – Gmt

回答

2

从理论上讲,两者都应该工作,因为std::thread具有可变参数的构造函数调用基本上它的参数就好像它是用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依靠可变参数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)); 
} 
+0

整洁!我expectind的boost ::不绑定:-) – Gmt

+0

工作我发现这里有趣的是,io_service对象::运行是不是一个静态的方法,不知道开机::绑定可如何结合到... – Gmt

+0

第一解决方案也提议工作。至少它编译vs2012 – Gmt