Difference between boost :: thread and std :: thread

I have a place where everything works using boost :: thread (example using 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); } 

If I try to use it with std: thread, I get a compilation error:

 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)); } 
+4
source share
1 answer

In theory, both should work, since std::thread has a vararg constructor, which basically calls its arguments, as if it were used with std::bind . The problem is that, at least in my implementation (gcc 4.6.3), neither std::thread nor std::bind can determine which run overload was intended, which leads to a compilation error.

However, if you use boost::bind , this works. Therefore, I would use and manually bind manually:

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

Edit: It looks like boost::bind succeeds because it received a ton of overloads and based on the number of arguments it was given, while resolving the overload and replacing the boost::bind template, it can determine what boost::asio::io_service::run overload is boost::asio::io_service::run was intended.

However, since std::bind and std::thread rely on vararg tempalte arguments, both run overloads are equally valid and the compiler cannot decide which one to use. This ambiguity leads to an inability to determine what results result from failures.

So another solution:

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

Source: https://habr.com/ru/post/1447255/


All Articles