死锁的概念

死锁的概念

Untitled

单个互斥量的例子

void * sellticket(void * arg) {
    // 卖票
    while(1) {
        // 加锁
        // 其他线程阻塞在此
        pthread_mutex_lock(&mutex);
        // 重复加锁
        // 第一个锁的持有线程阻塞在此
        pthread_mutex_lock(&mutex);

        if(tickets > 0) {
            usleep(6000);
            printf("%ld 正在卖第 %d 张门票\\n", pthread_self(), tickets);
            tickets--;
        }else {
            // 解锁
            pthread_mutex_unlock(&mutex);
            break;
        }

        // 解锁
        pthread_mutex_unlock(&mutex);
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
void * sellticket(void * arg) {
    // 卖票
    while(1) {
        // 加锁
        // 所有线程都阻塞在此
        pthread_mutex_lock(&mutex);

        if(tickets > 0) {
            usleep(6000);
            printf("%ld 正在卖第 %d 张门票\\n", pthread_self(), tickets);
            tickets--;
        }else {
            // 解锁
            pthread_mutex_unlock(&mutex);
            break;
        }

        // 忘记解锁
        // pthread_mutex_unlock(&mutex);
        // pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

多个互斥量的例子

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

// 创建2个互斥量
pthread_mutex_t mutex1, mutex2;

void * workA(void * arg) {
    pthread_mutex_lock(&mutex1);
    sleep(1);
    // 可能阻塞在此等待workB对mutex2解锁
    pthread_mutex_lock(&mutex2);

    printf("workA....\\n");

    pthread_mutex_unlock(&mutex2);
    pthread_mutex_unlock(&mutex1);
    return NULL;
}

void * workB(void * arg) {
    pthread_mutex_lock(&mutex2);
    sleep(1);
    // 可能阻塞在此等待workA对mutex1解锁
    pthread_mutex_lock(&mutex1);

    printf("workB....\\n");

    pthread_mutex_unlock(&mutex1);
    pthread_mutex_unlock(&mutex2);

    return NULL;
}

int main() {

    // 初始化互斥量
    pthread_mutex_init(&mutex1, NULL);
    pthread_mutex_init(&mutex2, NULL);

    // 创建2个子线程
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, workA, NULL);
    pthread_create(&tid2, NULL, workB, NULL);

    // 回收子线程资源
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    // 释放互斥量资源
    pthread_mutex_destroy(&mutex1);
    pthread_mutex_destroy(&mutex2);

    return 0;
}