Linux 线程同步-条件变量和互斥锁开发实例

Linux 线程同步-条件变量和互斥锁开发实例

场景

处理生产和消费问题, 生产过快,生产阻塞, 仓库满,消费过快,消费阻塞, 仓库空, 由于互斥锁存在,导致两种情况都会占用资源, 因此需要保持生产和消费的同步

代码

main.c

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

pthread_mutex_t mx_count=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
static int count=0;

void *thread_sub(void){
        while(1){
        printf("pthread sub lock\n");
        pthread_mutex_lock(&mx_count);
        printf("thread sub waitting...\n");
        pthread_cond_wait(&cond,&mx_count);
        count=count-1;
        printf("thread sub waitting finished\n");
        pthread_mutex_unlock(&mx_count);
        printf("pthread sub unlock\n");
        }
}

void *thread_add(void){
        while(1){
        printf("pthread add lock\n");
        pthread_mutex_lock(&mx_count);
        count=count+1;
        if(count%5==0){
                printf("thread add send signal\n");
                pthread_cond_signal(&cond);
                printf("thread add send signal finish\n");
        }
        pthread_mutex_unlock(&mx_count);
        printf("pthread add unlock\n");
        sleep(1);
        }
}

void main(void){
        pthread_t thrid_add, thrid_sub;
        int pthread_ret=-1;
        pthread_ret=pthread_create(&thrid_add, NULL, (void *)thread_add, NULL);
        if(pthread_ret){
                printf("pthread_create third add fail, exit\n");
                exit(EXIT_FAILURE);
        }
        pthread_ret=pthread_create(&thrid_sub, NULL, (void *)thread_sub, NULL);
        if(pthread_ret){
                printf("pthread create third sub fail, exit\n");
                exit(EXIT_FAILURE);
        }
        pthread_join(thrid_sub,NULL);
        exit(EXIT_SUCCESS);
}

执行结果

test@ubuntu: gcc -o main main.c -lpthread
test@ubuntu: ./main 
pthread sub lock
thread sub waitting...
pthread add lock
pthread add unlock
pthread add lock
pthread add unlock
pthread add lock
pthread add unlock
pthread add lock
pthread add unlock
pthread add lock
thread add send signal
thread add send signal finish
pthread add unlock
thread sub waitting finished
pthread sub unlock

结果分析

pthread_sub 一开始互斥锁加锁, 等待cond条件成立,系统将其加入等待条件队列中,同时对互斥锁解锁,pthread_add 可以访问资源count,待得到pthread_add 对cond 条件变量发出的信号并解锁后, pthread_sub 立即返回执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值