使用pthread的简单死锁示例

时间:2014-12-15 08:39:14

标签: c pthreads deadlock

我试图通过使用两个资源rs1和rs2的简单示例来理解死锁,两者都有自己的互斥锁,所以proc1锁定resource1并尝试获取resource2,同时proc2锁定resource2并尝试获取resource1,所以两者都处于僵局。以下程序显示死锁情况,但问题是为什么两个" p1试图获得rs2"和" p2争夺rs1"不是分别由proc1和proc2打印......

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

pthread_mutex_t resource1,resource2;
int test=0;
void *proc1()
{
    printf("\nThis is proc1 using rs1");
    pthread_mutex_lock(&resource1);
        usleep(200);
        printf("\np1 trying to get rs2..."); 
        pthread_mutex_lock(&resource2);
            test++;
        printf("\nproc1 got rs2!!");    
        pthread_mutex_unlock(&resource2);   
     pthread_mutex_unlock(&resource1);  
return 0;
}

void *proc2()
{
    printf("\nThis is proc2 using rs2");
    pthread_mutex_lock(&resource2);
        usleep(200);
        printf("\np2 trying to get rs1..."); 
        pthread_mutex_lock(&resource1);
            test--;
        printf("\nproc2 got rs1!!");    
        pthread_mutex_unlock(&resource1);   
     pthread_mutex_unlock(&resource2);  
return 0;
}

int main(){
    pthread_t t1,t2;
    pthread_mutex_init(&resource1, NULL);
    pthread_mutex_init(&resource2, NULL);

    pthread_create(&t1,NULL, proc1 , NULL);
    pthread_create(&t2,NULL, proc2 , NULL);

    pthread_join(t1,NULL);  
    pthread_join(t2,NULL);
// will never arrive here
    pthread_mutex_destroy(&resource1);
    pthread_mutex_destroy(&resource2);
}

2 个答案:

答案 0 :(得分:0)

这可能与您打印消息的方式有关。 stdout行缓冲,这意味着缓冲区在换行符上刷新。尝试在您打印的字符串中添加换行符 last ,或使用fflush显式刷新缓冲区。                      - 一些程序员老兄

答案 1 :(得分:0)

pthread_mutex_t lock1,lock2;

void * resource1(){

pthread_mutex_lock(&lock1);

printf("Job started in resource1..\n");
sleep(2);

printf("Trying to get resourc2\n");
pthread_mutex_lock(&lock2); 
printf("Aquired resourc2\n");
pthread_mutex_unlock(&lock2);

printf("Job finished in resource1..\n");

pthread_mutex_unlock(&lock1);

pthread_exit(NULL);

}

void * resource2(){

pthread_mutex_lock(&lock2);

printf("Job started in resource2..\n");
sleep(2);

printf("Trying to get resourc1\n");
pthread_mutex_lock(&lock1); 
printf("Aquired resourc1\n");
pthread_mutex_unlock(&lock1);

printf("Job finished in resource2..\n");

pthread_mutex_unlock(&lock2);

pthread_exit(NULL);

}

int main(){

pthread_mutex_init(&lock1,NULL);
pthread_mutex_init(&lock2,NULL);

pthread_t t1,t2;

pthread_create(&t1,NULL,resource1,NULL);
pthread_create(&t2,NULL,resource2,NULL);

pthread_join(t1,NULL);
pthread_join(t2,NULL);

return 0;

}

//这个程序按顺序执行,看看