Linux高性能服务器编程 14.8.2 14-3代码

为什么子进程会阻塞

文章中说,调用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仍然是上锁状态,因此子进程一直处于阻塞。

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值