为什么子进程会阻塞
文章中说,调用fork将创建一个子进程,子进程是调用fork线程的完整复制,同时子进程将继承父进程中的互斥锁的状态。子进程可能不清楚从父进程继承而来的互斥锁的具体状态。互斥锁可能被加锁了,但不是调用的哪个线程锁住的。(这里就有点迷)先看代码:
// An highlighted block
#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<wait.h>
pthread_mutex_t mutex;
void* another(void* arg){
printf("in child thread, lock the mutex\n");
pthread_mutex_lock(&mutex);
sleep(5);
pthread_mutex_unlock(&mutex);
printf("in child thread, unlock the mutex\n");
}
int main(){
pthread_mutex_init(&mutex, NULL);
pthread_t id;
pthread_create(&id, NULL, another, NULL);
sleep(1);
int pid = fork();
if(pid < 0){
pthread_join(id, NULL);
pthread_mutex_destroy(&mutex);
return 1;
}else if(pid == 0){
printf("I am in the child, want get the lock \n");
pthread_mutex_lock(&mutex);
printf("I can not run to hear...\n");
pthread_mutex_unlock(&mutex);
exit(0);
}else{
wait(NULL);
}
pthread_join(id, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
按照逻辑来说,create创建完another子线程之后,another线程会先获得锁,随后fork得到的子进程也执行进去获得锁但是阻塞住,随后another释放锁,子进程获得锁,休眠后解锁。但是实际情况不是这样,如图所示:
子进程在another子线程释放锁后并没有获得锁。
原因居然是!!!
子进程会复制父进程的数据,包括锁的状态,调用fork时父进程的mutex已经上锁了,这时调用fork子进程会复制另一把已经上锁的锁(不是mutex,假设为mutex2),因此,子进程试图给mutex2再次上锁,但是mutex2已经是处于上锁状态了,因此子进程会阻塞。当子线程为mutex解锁后,mutex2仍然是上锁状态,因此子进程一直处于阻塞。