在多线程中使用fork函数导致死锁,以及解决方案

在多线程编程中,如果某个线程调用了fork()函数创建子进程,创建的子进程将继承父进程所有的锁。

如果在父进程中加锁了,而在子进程中对锁重新加锁,将会导致死锁,以下是导致死锁的代码

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<wait.h>
#include<stdlib.h>
pthread_mutex_t mutex;

void *child(void *arg)
{
	printf("child thread add mutex
");
	pthread_mutex_lock(&mutex);
	//睡眠5秒是为了让主线程在创建子进程时,完成加锁操作
	sleep(5);
	pthread_mutex_unlock(&mutex);
}

int main()
{
	pthread_mutex_init(&mutex, NULL);
	pthread_t pid;
	pthread_create(&pid ,NULL, child, NULL);
	//睡眠1秒是为了子线程完成加锁
	sleep(1);
	pid = fork();
	if(pid < 0)
	{
		pthread_join(pid, NULL);
		pthread_mutex_destroy(&mutex);
		return 1;
	}
	else if(pid == 0)
	{
		printf("child process, get lock
");
		//由于子线程已经对锁进行了加锁操作,这里再次加锁时将会导致死锁
		pthread_mutex_lock(&mutex);
		printf("die mutex blocking
");
		pthread_mutex_unlock(&mutex);
		exit(0);
	}
	else
	{
		wait(NULL);
	}
	pthread_join(pid, NULL);
	pthread_mutex_destroy(&mutex);
	return 0;
}

解决方案:

可以使用pthread_atfork(), 清理线程中互斥锁的状态

函数原型:

#include<pthread.h>

pthread_atfork(void (*prepare)(void), void(*parent)(void), void(*child)(void))

prepare参数: 在fork()函数创建子进程之前调用,可以用来对多线程中的锁进行加锁操作

parent参数 : 在fork()函数创建子进程后,在fork()函数返回之前,在父进程中被执行,可以用来对多线程中的锁进行解锁操作

child参数 : 在fork()函数返回之前,在子进程中执行,可以用来对多线程中的锁进行解锁操作

修改后的代码

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<wait.h>
#include<stdlib.h>
pthread_mutex_t mutex;

void prepare()
{
	pthread_mutex_lock(&mutex);
}

void parent()
{
	pthread_mutex_unlock(&mutex);
}

void child()
{
	pthread_mutex_unlock(&mutex);
}
void *child(void *arg)
{
	printf("child thread add mutex
");
	pthread_mutex_lock(&mutex);
	//睡眠5秒是为了让主线程在创建子进程时,完成加锁操作
	sleep(5);
	pthread_mutex_unlock(&mutex);
}

int main()
{
	pthread_mutex_init(&mutex, NULL);
	pthread_t pid;
	pthread_create(&pid ,NULL, child, NULL);
	//睡眠1秒是为了子线程完成加锁
	sleep(1);
	//调用pthread_atfork()函数,对锁进行处理
	pthread_atfork(prepare, parent, child);
	pid = fork();
	if(pid < 0)
	{
		pthread_join(pid, NULL);
		pthread_mutex_destroy(&mutex);
		return 1;
	}
	else if(pid == 0)
	{
		printf("child process, get lock
");
		//由于子线程已经对锁进行了加锁操作,这里再次加锁时将会导致死锁
		pthread_mutex_lock(&mutex);
		printf("die mutex blocking
");
		pthread_mutex_unlock(&mutex);
		exit(0);
	}
	else
	{
		wait(NULL);
	}
	pthread_join(pid, NULL);
	pthread_mutex_destroy(&mutex);
	return 0;
}

经验分享 程序员 微信小程序 职场和发展