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

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

#include
#include
#include
#include
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;
}

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

Linux 线程同步(重要) 互斥量_第1张图片Linux 线程同步(重要) 互斥量_第2张图片Linux 线程同步(重要) 互斥量_第3张图片Linux 线程同步(重要) 互斥量_第4张图片

 

/*
    互斥量的类型 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
#include
#include
#include

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;
}

你可能感兴趣的:(Linux线程管理,Linux编程入门,linux,算法,运维)