手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Linux平台用C++实现事件对象,同步线程

[日期:2011-12-18] 来源:Linux社区  作者:chexlong [字体:大 中 小]

下边是测试代码

  1. // pthread_event.cpp : 定义控制台应用程序的入口点。   
  2. //   
  3.   
  4. #include <unistd.h>   
  5. #include "MyEvent.h"   
  6.   
  7. #define PRINT_TIMES 10   
  8.   
  9. //创建一个人工自动重置事件对象   
  10. CMyEvent g_myEvent;  
  11. int g_iNum = 0;  
  12.   
  13.   
  14. //线程函数1   
  15. void * ThreadProc1(void *pParam)  
  16. {  
  17.     for (int i = 0; i < PRINT_TIMES; i++)  
  18.     {  
  19.         g_iNum++;  
  20.         cout<<"ThreadProc1 do print, Num = "<<g_iNum<<endl;  
  21.   
  22.         //设置事件为有信号状态   
  23.         g_myEvent.Set();  
  24.   
  25.         sleep(1);  
  26.     }  
  27.   
  28.     return (void *)0;  
  29. }  
  30.   
  31. //线程函数2   
  32. void * ThreadProc2(void *pParam)  
  33. {  
  34.     bool bRet = false;  
  35.     while ( 1 )  
  36.     {  
  37.         if ( g_iNum >= PRINT_TIMES )  
  38.         {  
  39.             break;  
  40.         }  
  41.   
  42.         //以当前事件对象阻塞本线程,将其挂起   
  43.         bRet = g_myEvent.Wait();  
  44.         if ( bRet )  
  45.         {  
  46.             cout<<"ThreadProc2 do print, Num = "<<g_iNum<<endl;  
  47.   
  48.             //设置事件为无信号状态   
  49.             g_myEvent.Reset();  
  50.         }  
  51.         else  
  52.         {  
  53.             cout<<"ThreadProc2 system exception"<<endl;  
  54.         }  
  55.     }  
  56.   
  57.     return (void *)0;  
  58. }  
  59.   
  60.   
  61. int main(int argc, char* argv[])  
  62. {  
  63.     pthread_t thread1,thread2;  
  64.     pthread_attr_t attr1,attr2;  
  65.   
  66.   
  67.     //创建两个工作线程   
  68.     pthread_attr_init(&attr1);  
  69.     pthread_attr_setdetachstate(&attr1,PTHREAD_CREATE_JOINABLE);  
  70.     if (pthread_create(&thread1,&attr1, ThreadProc1,NULL) == -1)  
  71.     {  
  72.         cout<<"Thread 1: create failed"<<endl;  
  73.     }  
  74.     pthread_attr_init(&attr2);  
  75.     pthread_attr_setdetachstate(&attr2,PTHREAD_CREATE_JOINABLE);  
  76.     if (pthread_create(&thread2,&attr2, ThreadProc2,NULL) == -1)  
  77.     {  
  78.         cout<<"Thread 2: create failed"<<endl;  
  79.     }  
  80.   
  81.     //等待线程结束   
  82.     void *result;  
  83.     pthread_join(thread1,&result);  
  84.     pthread_join(thread2,&result);  
  85.   
  86.     //关闭线程,释放资源   
  87.     pthread_attr_destroy(&attr1);  
  88.     pthread_attr_destroy(&attr2);  
  89.   
  90.     int iWait;  
  91.     cin>>iWait;  
  92.   
  93.     return 0;  
  94. }  

编译,运行。可以看到,与Win32平台上的测试结果相同,好神奇!

linux
相关资讯       C++  Linux平台 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款