linux线程同步

个人测试:

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

char str[100];
pthread_mutex_t mutex_read,mutex_write;
pthread_cond_t cond_read,cond_write;
void* p1_func(void* arg)
{
  while(1)
  {
    pthread_mutex_lock(&mutex_read);
    pthread_cond_wait(&cond_read,&mutex_read);
    printf("\nstr=%s\n",str);
    pthread_cond_signal(&cond_write);
    pthread_mutex_unlock(&mutex_read);
  }
}
void* p2_func(void* arg)
{
  int i = 0;
  printf("\np2_func\n");
  while(1)
  {
     i++;
     if(i%10==0)
     {
//       printf("\n%d 10\n",i);
       pthread_mutex_lock(&mutex_write);
       sprintf(str,"lock %d",i);
       pthread_cond_signal(&cond_read);
       pthread_cond_wait(&cond_write,&mutex_write);
       pthread_mutex_unlock(&mutex_write);
     }
     sleep(1);
     printf("\n%d\n",i);
  }
}
int main()
{
  pthread_t p1;
  pthread_t p2;
  pthread_mutex_init(&mutex_read,NULL);
  pthread_cond_init(&cond_read,NULL);
  pthread_mutex_init(&mutex_write,NULL);
  pthread_cond_init(&cond_write,NULL);
  pthread_create(&p1,NULL,p1_func,NULL);
  pthread_create(&p2,NULL,p2_func,NULL); 
  pthread_join(p1,NULL);
  pthread_join(p2,NULL);
  pthread_mutex_destroy(&mutex_read);
  pthread_cond_destroy(&cond_read);
  pthread_mutex_destroy(&mutex_write);
  pthread_cond_destroy(&cond_write);
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值