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; }
Fabio
source share