c++ - What is the advantage of strand in boost asio? -


studying boost asio , find out class called "strand", far understand. if there 1 io_service associated specific strand , post handle strand.

example(from here)

boost::shared_ptr< boost::asio::io_service > io_service(      new boost::asio::io_service ); boost::shared_ptr< boost::asio::io_service::work > work(     new boost::asio::io_service::work( *io_service ) ); boost::asio::io_service::strand strand( *io_service );  boost::thread_group worker_threads; for( int x = 0; x < 2; ++x ) {     worker_threads.create_thread( boost::bind( &workerthread, io_service ) ); }  boost::this_thread::sleep( boost::posix_time::milliseconds( 1000 ) );  strand.post( boost::bind( &printnum, 1 ) ); strand.post( boost::bind( &printnum, 2 ) ); strand.post( boost::bind( &printnum, 3 ) ); strand.post( boost::bind( &printnum, 4 ) ); strand.post( boost::bind( &printnum, 5 ) ); 

then strand serialized handler execution us.but benefits of doing this?why don't create single thread(ex : make x = 1 in loop) if want tasks become serialized?

think of system single io_service manages sockets hundreds of network connections. able parallelize workload, system maintains pool of worker threads call io_service::run.

now of operations in such system can run in parallel. have serialized. example, not want multiple write operations on same socket happen concurrently. use 1 strand per socket synchronize writes: writes on distinct sockets can still happen @ same time, while writes same sockets serialized. worker threads not have care synchronization or different sockets, grab whatever io_service::run hands them.

one might ask: why can't use mutex instead synchronization? advantage of strand worker thread not scheduled in first place if strand being worked on. mutex, worker thread callback , block on lock attempt, preventing thread doing useful work until mutex becomes available.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -