執行緒中呼叫fork函式,鎖的變化

Amiayy發表於2017-08-11

一、執行緒中呼叫fork函式鎖的變化
舉例說明:在下列程式碼中的排程變化。
這裡寫圖片描述

但是在fork前加鎖再解鎖不安全,所以在fork函式裡引用pthread_atfork(prepare,parent,child).其中三個引數均為函式指標。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <pthread.h>

pthread_mutex_t mutex;

void* fun(void *arg)
{
        printf("fun will get mutex\n");
        pthread_mutex_lock(&mutex);
        printf("fun lock success\n");
        sleep(5);
        pthread_mutex_unlock(&mutex);
        printf("fun unlock\n");

}

void prepare()
{
    pthread_mutex_lock(&mutex);
}
void parent()
{
    pthread_mutex_unlock(&mutex);
}
void child()
{
    pthread_mutex_unlock(&mutex);
}

void main()
{
    pthread_mutex_init(&mutex,NULL);
    pthread_t th;
    int res=pthread_create(&th,NULL,fun,NULL);
    assert(res==0);

    sleep(2);

    pthread_atfork(prepare,parent,child);

    pid_t pid=fork();
    assert(pid!=-1);
    if(pid==0)
    {
        printf("child will get mutex\n");
        pthread_mutex_lock(&mutex);
        printf("child lock success\n");
        sleep(2);
        pthread_mutex_unlock(&mutex);
        printf("child unlock\n");
    }
    else
    {
        printf("father will get mutex\n");
        pthread_mutex_lock(&mutex);
        printf("father lock success\n");
        sleep(2);
        pthread_mutex_unlock(&mutex);
        printf("father unlock\n");
    }

}

列印結果:
fun will get mutex
fun lock success
fun unlock
father will get mutex
father lock success
child will get mutex
child lock success
father unlock
child unlock

相關文章