首页 > 编程 > 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. { 
  11.   struct timespec sleepTime; 
  12.   struct timespec returnTime; 
  13.   sleepTime.tv_sec = sec; 
  14.   sleepTime.tv_nsec = nsec; 
  15.   nanosleep(&sleepTime, &returnTime); 
  16. } 
  17. void test1() 
  18. { 
  19.   m_threadSleep(1,0); 
  20.   printf("I'm thread1 .../r/n"); 
  21. } 
  22. void test2() 
  23. { 
  24.   m_threadSleep(2,0); 
  25.   printf("I'm thread2 .../r/n"); 
  26. } 
  27. int main() 
  28. { 
  29.   pthread_t thread1,thread2; 
  30.   void *result; 
  31.   time_t tbegin,tend; 
  32.   tbegin = time(NULL); 
  33.   pthread_create(&thread1,NULL,(void*)&test1,NULL); 
  34.   pthread_create(&thread2,NULL,(void*)&test2,NULL); 
  35.   pthread_join(thread1,&result); 
  36.   pthread_join(thread2,&result); 
  37.   tend = time(NULL); 
  38.   printf("%d/r/n",tend-tbegin); 
  39.   return 0; 
  40. } 
?

编译代码如下:
 

  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. { 
  12.   boost::xtime t; 
  13.   boost::xtime_get(&t, boost::TIME_UTC); 
  14.   t.sec += sec; 
  15.   t.nsec += nsec; 
  16.   return t; 
  17. } 
  18. void test1() 
  19. { 
  20.   boost::this_thread::sleep(getSleepTime(1,500)); 
  21.   std::cout <<"I'm thread1 !"<< std::endl; 
  22. } 
  23. void test2() 
  24. { 
  25.   boost::this_thread::sleep(getSleepTime(3,500)); 
  26.   std::cout <<"I'm thread2 !"<< std::endl; 
  27. } 
  28.  
  29. int main(int argc, char* argv[]) 
  30. { 
  31.   boost::thread thrd1(&test1); 
  32.   boost::thread thrd2(&test2); 
  33.   std::time_t t_begin,t_end; 
  34.   t_begin = time(NULL); 
  35.   thrd1.join(); 
  36.   thrd2.join(); 
  37.   t_end = time(NULL); 
  38.   std::cout<<t_end-t_begin<<std::endl; 
  39.   return 0; 
  40. } 
?

编译命令如下:
 

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

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

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