Linux 线程同步(重要) 互斥量

/*
    三个窗口卖一百张票
*/

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>
int tickets = 0;
void * sellticket(void * arg) {
    //卖票
    usleep(7000);
    while(tickets <= 100) {
        printf("%ld 正在卖第 %d 张票\n", pthread_self(), tickets);
        tickets++;
    }
    return NULL;
}



int main() {

    //创建子线程
    pthread_t tid1, tid2, tid3;
    pthread_create(&tid1, NULL, sellticket, NULL);
    pthread_create(&tid2, NULL, sellticket, NULL);
    pthread_create(&tid3, NULL, sellticket, NULL);

    pthread_detach(tid1);
    pthread_detach(tid2);
    pthread_detach(tid3);
   
    pthread_exit(NULL);
    return 0;
}

当多线程对共享的资源同时进行处理时,可能出现三个线程同时使用一个变量,会出现三个线程都输出正在卖第一百张票的情况

 

/*
    互斥量的类型 pthread_mutex_t
    int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
        初始化互斥量
        参数:
            -mutex 需要初始化的变量
            -attr 互斥量相关的属性 一般使用默认 传入NULL
        - restrict C语言的修饰符,被修饰的指针不能由另外的指针进行操作
            
    int pthread_mutex_destory(pthread_mutex_t *mutex)
        -释放互斥量的资源
    int pthread_mutex_lock(pthread_mutex_t *mutex)
        -加锁 (阻塞)
    int pthread_mutex_trylock(pthread_mutex_t *mutex)
        -加锁,尝试加锁,如果加锁失败,不会阻塞,直接返回
    int pthread_mutex_unlock(pthread_mutex_t *mutex);
        -解锁
*/

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>

int tickets = 0;

pthread_mutex_t mutex;

void * sellticket(void * arg) {
    //卖票
    while(1) {
        pthread_mutex_lock(&mutex);
        if(tickets <= 1000) {
            usleep(600);
            printf("%ld 正在卖第 %d 张票\n", pthread_self(), tickets);
            tickets++;
        }
        else {
            pthread_mutex_unlock(&mutex);
            break;
        }
        //解锁
        pthread_mutex_unlock(&mutex);
    }  
    return NULL;
}

int main() {
    //初始化互斥量
    pthread_mutex_init(&mutex, NULL);

    //创建子线程
    pthread_t tid1, tid2, tid3;
    pthread_create(&tid1, NULL, sellticket, NULL);
    pthread_create(&tid2, NULL, sellticket, NULL);
    pthread_create(&tid3, NULL, sellticket, NULL);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);
   
    pthread_exit(NULL);

    pthread_mutex_destroy(&mutex);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值