首页 > 编程 > C++ > 正文

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

2020-05-23 14:20:44
字体:
来源:转载
供稿:网友

本文实例讲述了基于C++实现的线程休眠代码,分享给大家供大家参考。具体方法如下:

linux平台示例如下:

 

  1. /* 
  2. File   : thread1.c 
  3. Author  : Mike 
  4. E-Mail  : Mike_Zhang@live.com 
  5. */ 
  6. #include <stdio.h> 
  7. #include <pthread.h> 
  8. #include <time.h> 
  9. void m_threadSleep(int sec,int nsec) 
  10.   struct timespec sleepTime; 
  11.   struct timespec returnTime; 
  12.   sleepTime.tv_sec = sec; 
  13.   sleepTime.tv_nsec = nsec; 
  14.   nanosleep(&sleepTime, &returnTime); 
  15. void test1() 
  16.   m_threadSleep(1,0); 
  17.   printf("I'm thread1 .../r/n"); 
  18. void test2() 
  19.   m_threadSleep(2,0); 
  20.   printf("I'm thread2 .../r/n"); 
  21. int main() 
  22.   pthread_t thread1,thread2; 
  23.   void *result; 
  24.   time_t tbegin,tend; 
  25.   tbegin = time(NULL); 
  26.   pthread_create(&thread1,NULL,(void*)&test1,NULL); 
  27.   pthread_create(&thread2,NULL,(void*)&test2,NULL); 
  28.   pthread_join(thread1,&result); 
  29.   pthread_join(thread2,&result); 
  30.   tend = time(NULL); 
  31.   printf("%d/r/n",tend-tbegin); 
  32.   return 0; 
?

编译代码如下:
 

  1. gcc thread1.c -o thread1 -lpthread 
?

boost库实现示例如下:

 

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

编译命令如下:
 

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

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表