Wednesday 15 April 2015

c++ - avoiding busy wait with boost::asio poll -



c++ - avoiding busy wait with boost::asio poll -

i'm writing service on linux uses boost::asio::io_service io_service::poll in while loop. busy wait loop, e.g. wastes cpu cycles.

void application::run() { seek { std::cout << "tcpserver starting..\n"; _tcpserver.reset( new tcpserver(_io_service, boost::ref(_spstate)) ); // _io_service.run(); while( ! _spstate->quitsignalled() ) { _io_service.poll(); } std::cerr << "quit signalled, tcpserver stopping.. :/" << std::endl; } catch(std::exception & e) { std::cout << e.what() << "\n"; } }

i utilize poll instead of run check if thread in service has signalled service shutdown.

is there way of achieving without using poll in busy wait loop ?

the service uses async io on single thread, , other threads info processing.

i've added sleep between iterations of loop seems cut down waste of cpu time, hoping there might more efficient way?

void application::run() { using boost::this_thread::sleep_for; static const boost::chrono::milliseconds napmsecs( 50 ); seek { std::cout << "tcpserver starting..\n"; _tcpserver.reset( new tcpserver(_io_service, boost::ref(_spstate)) ); // _io_service.run(); while( ! _spstate->quitsignalled() ) { _io_service.poll(); boost::this_thread::sleep_for( napmsecs ); } std::cerr << "quit signalled, tcpserver stopping.. :/" << std::endl; } catch(std::exception & e) { std::cout << e.what() << "\n"; } }

i'd say, take advantage of fact boost::asio::io_service threadsafe default, , do

iosvc.run();

and signal service shutdown on "another thread in service" would:

iosvc.stop();

remember iosvc.reset() before phone call {run,poll}[_one] again, per documentation.

of course of study can utilize other means signal actual logical workers end, that's independent unrelated boost asio

c++ boost-asio busy-waiting

No comments:

Post a Comment