Linux下多线程打印奇数偶数

练习Linux多线程环境下的第一个例程:
存在三个不同的线程:
线程1只输出----------。
线程2只输出偶数。
线程3只输出奇数。
结果输出:

-----------
0
-----------
1
-----------
2
-----------
3

一直到:

-----------
999
-----------
1000

定义结构体:struct oddevenzero_t

struct oddevenzero_t
  8 {   
  9     pthread_mutex_t mu_odd;  
 10     pthread_mutex_t mu_even;  
 11     pthread_mutex_t mu_zero;
 12     int n;
 13     int num;
 14 };
 15
 16 struct oddevenzero_t *test;

线程和互斥锁创建:

int main()
 64 {
 65     pthread_t tid;
 66     int ret, i = 0;
 67     test = (struct oddevenzero_t*)malloc(sizeof(struct oddevenzero_t));
 68     pthread_mutex_init(&test->mu_odd, NULL);
 69     pthread_mutex_init(&test->mu_zero, NULL);
 70     pthread_mutex_init(&test->mu_even, NULL);
 71     pthread_mutex_lock(&test->mu_odd);
 72     pthread_mutex_lock(&test->mu_even);
 73     pthread_mutex_unlock(&test->mu_zero);
 74     test->n = 1000 + 1;
 75     test->num = 0;
 76     for(i = 1; i <= 3; i++)
 77     {
 78         ret = pthread_create(&tid, NULL, task, (void*)i);
 80         pthread_detach(tid);
 81 
 82         if(ret != 0)
 83         {
 84             fprintf(stderr, "creat thread err:%s\n", strerror(ret));
 85             exit(1);
 86         }
 87     }
 89     sleep(1);
 90     return 0;
 91 }

线程函数:

19 void *task(void *arg)
 20 {
 21     if((int)arg == 1)
 22     {
 24         while(1){
 25             pthread_mutex_lock(&test->mu_zero);
 26             if(test->num%2 == 0){
 27                 printf("-----------\n");
 28                 pthread_mutex_unlock(&test->mu_odd);
 29             }
 30             else{
 31                 printf("-----------\n");
 32                 pthread_mutex_unlock(&test->mu_even);
 33             }
 34         }
 35     }
 36     if((int)arg == 2)
 37     {
 39         while(1){
 40             pthread_mutex_lock(&test->mu_odd);
 41             printf("%d\n", test->num);
 42             test->num ++;
 43             if(test->num < test->n){
 44                 pthread_mutex_unlock(&test->mu_zero);
 45             }
 46         }
 47     }
 48     if((int)arg == 3)
 49     {
 51         while(1){
 52             pthread_mutex_lock(&test->mu_even);
 53             printf("%d\n", test->num);
 54             test->num ++;
 55             if(test->num < test->n){
 56                 pthread_mutex_unlock(&test->mu_zero);
 57             }
 58         }
 59     }
 60     return NULL;
 61 }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值