The main use of the previous method is: through the thread delay real
Current timing, and can only be scheduled once, if the need for this timing processing, you need to use the following timer;
#include "stdafx.h" #include <iostream> #include <boost/asio.hpp> #include <boost/thread.hpp># Include <boost/date_time/posix_time/posix_time.hpp>using namespace boost::asio;using namespace boost;using namespace std;//Loop State enum program_state{state1,state2,state3,state4};/* The function of the Timer class: When the timeout function of the external class is passed in, it is called in the Timer timeout function; The relationship between such classes is clear */class ctimer{private:int_timeout_len;bool_is_remove_when_timeout;//boost::function<void () > f;//delegate function type is no parameter no return value thread* ptrthread;public://external function//~ctimer () {if (Ptrthread! = NULL) {Delete this->ptrthread;this- >ptrthread = NULL;}} Template<typename f>void Installtimer (f F, int _timeout_len, bool _is_remove_when_timeout) {This->_timeout_ Len = _timeout_len;this->_is_remove_when_timeout = _is_remove_when_timeout;this->f = f;//Open Thread ptrthread=new Thread (Bind (&ctimer::settimer, this));} void Removetimer () {this->_is_remove_when_timeout = True;this->_timeout_len = 1;this->f = NULL;} Timer thread worker function void SetTimer () {Io_service M_ios;//Set timer and set callback function Deadline_timer T (M_ios, Boost::p osix_time::millisec (This->_timeout_len)); T.async_wait (Bind ( &ctimer::timeout,this));//callback//block here, wait for event M_ios.run (); cout << "thread Quit" <<ENDL;} callback function void Timeout () {///callback function called outside handler if (This->f!=null) this->f (); if (this->_is_remove_when_timeout = = False) {thread (bind (&ctimer::settimer, this));}}};/ /test class, worker main class testclassa{public://Timer class object ctimer* Ptrtimer; Testclassa () {state = State1;ptrtimer = new Ctimer;} ~testclassa () {delete ptrtimer;} Main program Current state program_state state;//Current state timer timeout handler void Timeoutcallbackprint () {printf ("timeoutcallbackprint\n"); Ptrtimer->removetimer ();//Direct-off timer this->state = State2;} void Run () {while (1) {//state loop Scan Switch (this->state) {case state1:proc_state1 (); Break;case state2:break;}}} The current state of the main program, the processing function void Proc_state1 () {//Join the timer, and the required handler function of the timer callback function is passed in, and the parameters are passed into the Ptrtimer->installtimer (Bind (& Testclassa::timeoutcallbackprint,this);//Dead loop, sending and receiving processing while (this->state = = state1) {}}};int _tmAin (int argc, _tchar* argv[]) {Testclassa *TC = new Testclassa (); Tc->run ();//The main program loops through the class GetChar (); return 0;}
Use the boost thread timer as a background thread to toggle the main loop program State Method 2