多线程造成死锁的两种情况

*
 * 程序中使用一个以上的互斥量造成程序死锁
 */
#include
#include
#include
//定义两个互斥锁并初始化
pthread_mutex_t ALock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t BLock = PTHREAD_MUTEX_INITIALIZER;

/*
 * 功能:线程1函数
 */
void* thread1_func(void *arg)
{
    //sleep(1);
    pthread_mutex_lock(&ALock);
    sleep(2);
    printf("thread 1 lock ALock, wanting get BLock...\n");
    pthread_mutex_lock(&BLock);
    printf("thread 1 get BLock\n");
    pthread_mutex_unlock(&BLock);
    pthread_mutex_unlock(&ALock);
    pthread_exit(NULL);
}

/*
 * 功能:线程而2函数
 */
void* thread2_func(void *arg)
{
    sleep(1);
    pthread_mutex_lock(&BLock);
    printf("thread 2 lock BLock, wating get ALock...\n");
    pthread_mutex_lock(&ALock);
    printf("thread 2 get ALock\n");
    pthread_mutex_unlock(&ALock);
    pthread_mutex_unlock(&BLock);
    pthread_exit(NULL);
}

int main(void)
{
    pthread_t thid1, thid2;

    pthread_create(&thid1, NULL, thread1_func, NULL);
    pthread_create(&thid2, NULL, thread2_func, NULL);

    pthread_join(thid1, NULL);
    pthread_join(thid2, NULL);
    printf("main thread exit\n");
    exit(0);
}

#include
#include
#include
//在同一个线程对同一个互斥量加锁两次会出现死锁
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;//定义一个互斥量,并对其进行初始化
int a = 6;

/*void* thread_func(void *arg)
{
    pthread_mutex_lock(&lock);
    pthread_mutex_lock(&lock);
    printf("thread a = %d\n", a);
    pthread_mutex_unlock(&lock);
    pthread_exit(NULL);
}*/
int main(void)
{
    pthread_mutex_lock(&lock);
    pthread_mutex_lock(&lock);//对一个互斥量加锁两次,出现死锁
    printf("%d\n", a);//永远不会执行到这里
    pthread_mutex_unlock(&lock);
    exit(EXIT_SUCCESS);

/*  int err;
    pthread_t thid;

    err = pthread_create(&thid, NULL, thread_func, NULL);
    if(err != 0)
    {
        printf("pthread_create failed\n");
        exit(EXIT_FAILURE);
    }
    pthread_join(thid, NULL);
    printf("main thread a = %d\n",a);
    exit(EXIT_SUCCESS);*/
}

你可能感兴趣的:(Linux系统编程)