基于C++实现的线程休眠代码

2020-01-06 13:03:57丽君
?

boost库实现示例如下:

 

  1. /*  File   : boost_thread1.cpp 
  2. Author  : Mike  E-Mail  : Mike_Zhang@live.com 
  3. */  #include <boost/date_time/posix_time/posix_time.hpp> 
  4. #include <boost/thread/thread.hpp>  #include <iostream> 
  5.   boost::xtime getSleepTime(int sec,int nsec) 
  6. {    boost::xtime t; 
  7.   boost::xtime_get(&t, boost::TIME_UTC);    t.sec += sec; 
  8.   t.nsec += nsec;    return t; 
  9. }  void test1() 
  10. {    boost::this_thread::sleep(getSleepTime(1,500)); 
  11.   std::cout <<"I'm thread1 !"<< std::endl;  } 
  12. void test2()  { 
  13.   boost::this_thread::sleep(getSleepTime(3,500));    std::cout <<"I'm thread2 !"<< std::endl; 
  14. }   
  15. int main(int argc, char* argv[])  { 
  16.   boost::thread thrd1(&test1);    boost::thread thrd2(&test2); 
  17.   std::time_t t_begin,t_end;    t_begin = time(NULL); 
  18.   thrd1.join();    thrd2.join(); 
  19.   t_end = time(NULL);    std::cout<<t_end-t_begin<<std::endl; 
  20.   return 0;  } 
?

编译命令如下:
 

  1. g++ boost_thread1.cpp -o boost_thread1 -lboost_thread-mt 
?

希望本文所述对大家的C++程序设计有所帮助。