国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

基于C++實(shí)現(xiàn)的線程休眠代碼

2020-05-23 14:20:44
字體:
供稿:網(wǎng)友

本文實(shí)例講述了基于C++實(shí)現(xiàn)的線程休眠代碼,分享給大家供大家參考。具體方法如下:

linux平臺(tái)示例如下:

 

  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庫實(shí)現(xiàn)示例如下:

 

  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 
?

希望本文所述對(duì)大家的C++程序設(shè)計(jì)有所幫助。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 宾阳县| 镇雄县| 团风县| 北流市| 贵阳市| 彭泽县| 宁化县| 高平市| 黄石市| 茶陵县| 阳西县| 全椒县| 锡林郭勒盟| 天全县| 合肥市| 视频| 巫山县| 辽阳市| 洱源县| 五河县| 长葛市| 瑞丽市| 洛浦县| 嘉荫县| 安陆市| 万源市| 犍为县| 泾阳县| 海口市| 宜良县| 尼木县| 开封县| 绥棱县| 那曲县| 文水县| 龙里县| 北宁市| 上高县| 东乌| 洪江市| 西和县|