Linux多线程——线程同步与互斥(3)条件变量

代码:

条件变量

#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#define Max 100
pthread_mutex_t mutex;
pthread_cond_t conditional_m;
int global=0;
void *thread_1_exe(void *flag){
      while(global<Max){
      pthread_mutex_lock(&mutex);
      if(global%8==0)  pthread_cond_signal(&conditional_m);//unlock mutex
      else        printf("In thread 1 global=%d\n",global);
      pthread_mutex_unlock(&mutex);
      sleep(1);
      global++;
      }
}
void *thread_2_exe(void *flag){
      while(global<Max){
      pthread_mutex_lock(&mutex);
      if(global%8!=0)
         pthread_cond_wait(&conditional_m,&mutex);
      else
         printf("Thread 2:global=%4d\n",global);
      pthread_mutex_unlock(&mutex);
      sleep(1);
      }
}
int main(void){
    pthread_t thread_1;
    pthread_t thread_2;
    int error1,error2;
    pthread_mutex_init(&mutex,NULL);//mutex type:default
    pthread_cond_init(&conditional_m,NULL);
    error1=pthread_create(&thread_1,NULL,thread_1_exe,(void *)NULL);
    error2=pthread_create(&thread_2,NULL,thread_2_exe,(void *)NULL);
    if(error1!=0||error2!=0){
        printf("thread create error\n ");
    }
    pthread_join(thread_2,NULL);//NULL:message from pthread_exit()
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&conditional_m);
    getchar();
    return 1;
}

线程创建  线程退出 线程同步与互斥

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值