首页 > > > 两个线程,两个互斥锁,怎么形成一个死循环?
关注+星标公众号,不错过精彩内容

转自 | 一口Linux
程序流程图如下:

如上图所示:
【注意】为了保证主线程和子线程都能够分别获得锁mutex1、mutex2,各自获得锁后一定要先sleep 1秒钟,否则创建完子线程后,主线程还有一定的时间片,主线程会申请到锁mutex2,无法形成死锁。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
unsigned int value1, value2, count;
pthread_mutex_t mutex1,mutex2;
void *function(void *arg);
void *function(void *arg)
{
pthread_mutex_lock(&mutex2);
printf("new thread get mutex2\n");
sleep(1);
pthread_mutex_lock(&mutex1);
printf("new thread get mutex1\n");
pthread_mutex_unlock(&mutex1);
printf("new thread release mutex1\n");
pthread_mutex_unlock(&mutex2);
printf("new thread release mutex2\n");
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t a_thread;
if (pthread_mutex_init(&mutex1, NULL) < )
{
perror("fail to mutex_init");
exit(-1);
}
if (pthread_mutex_init(&mutex2, NULL) < )
{
perror("fail to mutex_init");
exit(-1);
}
if (pthread_create(&a_thread, NULL, function, NULL) < )
{
perror("fail to pthread_create");
exit(-1);
}
while ( 1 )
{
pthread_mutex_lock(&mutex1);
printf("main thread get mutex1\n");
sleep(1);
pthread_mutex_lock(&mutex2);
printf("main thread get mutex2\n");
pthread_mutex_unlock(&mutex2);
printf("main thread release mutex2\n");
pthread_mutex_unlock(&mutex1);
printf("main thread release mutex1\n");
}
return ;
}
从执行结果可以判断,主线程和子线程分别获得了互斥锁mutex1、mutex2,sleep 1秒后,他们都想再分别申请mutex2、mutex1,而双方都不想释放自己手中的锁,锁已形成了死锁,程序就一直处于休眠状态。
查看进程ID,为4204
查看该进程创建的线程id:4204、4205。

点击“阅读原文”查看更多分享,欢迎点分享、收藏、点赞、在看。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/9525959/viewspace-3140253/ ,如需转载,请注明出处,否则将追究法律责任。