Linux多线程编程

  1. #include <pthread.h>  
  2. #include <stdio.h>  
  3. #include <sys/time.h>  
  4. #include <string.h>  
  5. #define MAX 10  
  6. pthread_t thread[2];  
  7. pthread_mutex_t mut;  
  8. int number=0, i;  

  9. void *thread1()  
  10. {  
  11.         printf ("thread1 : I'm thread 1\n");  
  12.         for (i = 0; i < MAX; i++)  
  13.         {  
  14.                 printf("thread1 : number = %d\n",number);  
  15.                 pthread_mutex_lock(&mut);  
  16.                         number++;  
  17.                 pthread_mutex_unlock(&mut);  
  18.                 sleep(2);  
  19.         }  
  20.         printf("thread1 :主函数在等我完成任务吗?\n");  
  21.         pthread_exit(NULL);  
  22. }  
  23. void *thread2()  
  24. {  
  25.         printf("thread2 : I'm thread 2\n");  
  26.         for (i = 0; i < MAX; i++)  
  27.         {  
  28.                 printf("thread2 : number = %d\n",number);  
  29.                 pthread_mutex_lock(&mut);  
  30.                         number++;  
  31.                 pthread_mutex_unlock(&mut);  
  32.                 sleep(3);  
  33.         }  
  34.         printf("thread2 :主函数在等我完成任务吗?\n");  
  35.         pthread_exit(NULL);  
  36. }  
  37. void thread_create(void)  
  38. {  
  39.         int temp;  
  40.         memset(&thread, 0, sizeof(thread));          //comment1  
  41.         /*创建线程*/  
  42.         if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0)       //comment2  
  43.                 printf("线程1创建失败!\n");  
  44.         else  
  45.                 printf("线程1被创建\n");  
  46.         if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0)  //comment3  
  47.                 printf("线程2创建失败");  
  48.         else  
  49.                 printf("线程2被创建\n");  
  50. }  
  51. void thread_wait(void)  
  52. {  
  53.         /*等待线程结束*/  
  54.         if(thread[0] !=0) {                   //comment4  
  55.                 pthread_join(thread[0],NULL);  
  56.                 printf("线程1已经结束\n");  
  57.         }  
  58.         if(thread[1] !=0) {                //comment5  
  59.                 pthread_join(thread[1],NULL);  
  60.                 printf("线程2已经结束\n");  
  61.         }  
  62. }  
  63. int main()  
  64. {  
  65.         /*用默认属性初始化互斥锁*/  
  66.         pthread_mutex_init(&mut,NULL);  
  67.         printf("我是主函数哦,我正在创建线程,呵呵\n");  
  68.         thread_create();  
  69.         printf("我是主函数哦,我正在等待线程完成任务阿,呵呵\n");  
  70.         thread_wait();  
  71.         return 0;  
  72. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值