Is it boost :: io_service :: post thread safe?

Is streaming new handlers from a handler safe? That is, can threads called io_service::run() host new handlers for the same io_service?

thanks

+7
source share
3 answers

It is safe to send handlers from a handler for a single io_service instance according to the documentation.

Thread safety

Individual objects : safe.

Common objects : safe, except that it calls reset (), but there are incomplete run (), run_one (), poll (), or poll_one () calls undefined results.

+7
source

Without interfering with too much knowledge of the exact topics that you mentioned there, I would say:

link: http://www.boost.org/doc/libs/1_46_1/doc/html/boost_asio/reference/io_service__strand.html

+1
source

I think this is not because the following code did not return 3000000, and I did not see mutex synchronize the internal io_service queue without blocking.

 #include <boost/asio/io_service.hpp> #include <boost/thread.hpp> #include <boost/thread/detail/thread_group.hpp> #include <memory> void postInc(boost::asio::io_service *service, std::atomic_int *counter) { for(int i = 0; i < 100000; i++) service->post([counter] { (*counter)++; }); } int main(int argc, char **argv) { std::atomic_int counter(0); { boost::asio::io_service service; boost::asio::io_service::work working(service); boost::thread_group workers; for(size_t i = 0; i < 10;++i) workers.create_thread(boost::bind(&boost::asio::io_service::run, &service)); boost::thread_group producers; for (int it = 0; it < 30; it++) { producers.add_thread(new boost::thread(boost::bind(postInc,&service,&counter))); } producers.join_all(); std::cout << "producers ended" << std::endl; service.stop(); workers.join_all(); } std::cout << counter.load(); char c; std::cin >> c; return 0; } 
0
source

All Articles