有关pthread锁和条件同步

代码:

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h> //getopt_long()头文件位置    
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <pthread.h>

void *thread1_function(void *arg);
void *thread2_function(void *arg);
pthread_mutex_t mutex;
pthread_cond_t cond;
int g_value = 0;
int main(int argc, char *argv[])
{
    int rc1,rc2;
    char *str1="wenhaoll";
    char *str2="linglong";
    pthread_t thread1,thread2;

    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&cond,NULL);
    if((rc1 = pthread_create(&thread1,NULL,thread1_function,str1)))
    {
        fprintf(stdout,"thread 1 create failed: %d\n",rc1);
    }

    if((rc2 = pthread_create(&thread2,NULL,thread2_function,str2)))
    {
        fprintf(stdout,"thread 2 create failed: %d\n",rc2);
    }

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    return 0;
}

void *thread1_function(void *arg)
{
   pthread_cond_wait(&cond, &mutex);
   char i;
   for (i=0; i<9; i++)
   {
      pthread_mutex_lock(&mutex);
      g_value ++;
      pthread_cond_signal(&cond);
      pthread_mutex_unlock(&mutex);
      sleep(2);
   }
   return NULL;
}
void *thread2_function(void *arg)
{
   char i;
   for (i=0; i<9; i++)
   {
      pthread_mutex_lock(&mutex);
      pthread_cond_wait(&cond, &mutex);
      printf("g_value is: %d\n", g_value);
      pthread_mutex_unlock(&mutex);
   }
   return NULL;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值