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

来源:互联网 发布:暗黑战神源码解读 编辑:程序博客网 时间:2024/05/14 16:46
* * 程序中使用一个以上的互斥量造成程序死锁 */#include<stdio.h>#include<stdlib.h>#include<pthread.h>//定义两个互斥锁并初始化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<stdio.h>#include<stdlib.h>#include<pthread.h>//在同一个线程对同一个互斥量加锁两次会出现死锁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);*/}
阅读全文
0 0
原创粉丝点击