多线程中atfokr的使用

来源:互联网 发布:linux 查看gpu显存 编辑:程序博客网 时间:2024/05/16 05:38
#include <sys/types.h>
#include <pthread.h>
#include <sys/wait.h>
#include "errors.h"


pid_t self_pid;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;


void fork_prepare(void)
{
int status;
status = pthread_mutex_lock(&mutex);
if(status != 0)
err_abort(status,"Lock in prepare handler");
}


void fork_parent(void)
{
int status ;
status = pthread_mutex_unlock(&mutex);
if(status != 0)
err_abort(status,"Unlock in parent handler");
}


void fork_child(void)
{
self_pid = getpod();
status = pthread_mutex_unlock(&mutex);
if(status != 0)
err_abort(status,"Unlock in child handler");
}


void *thread_routine(void *arg)
{
pid_t child_pid;
int stauts;
child_pid = fork();
if(child_pid ==(pid_t)-1)
err_abort("Fork");
status = pthread_mutex_lock(&mutex);
if(status != 0)
err_abort(status,"Lock in child");
status = pthread_mutex_unlcok(&mutex);
if(status != 0)
err_abort(status,"Unlock in child");
printf("After fork :%d(%d)\n",child_pid,self_pid);
if(child_pid != 0)
{
if((pid_t)-1 == waitpid(child_pid,(int*)0,0))
errno_abort("Wait for child");
}
return NULL;
}
int main(int argc,char *argv[])
{
pthread_t fork_thread;
int atfork_flag = 1;
int status;
if(argc >1)
atfork_flag = atoi(argv[1]);
if(atfork_flag)
{
status = pthread_atfork(fork_prepare,fork_parent,fork_child);
if(status != 0)
err_abort(status,"Register fork handlers");
}
self_pid = getpid();
status = pthread_mutex_lock(&mutex);
if(status != 0)
err_abort(status,"Lock mutex");
status = pthread_create(&fork_thread,NULL,thread_routine,NULL);
if(status != 0)
err_abort(stauts,"Unlock mutex");
status = pthread_join(fork_thread,NULL);
if(status != 0)
err_abort(status,"Join thread);
return 0;


}


fork_prepare是prepare处理器,在创建子进程前,它将在父进程内被fork调用。该函数改变的任何状态(特别是被锁住的互斥量)将被拷贝进子进程。fork_prepare函数锁住程序的互斥量。

函数fork_parent式parent处理器,在创建子进程以后,它将在父进程内被fork调用,总的来说,一个parent处理器,应该取消在prepare处理器中做的处理,以便在父进程能正常继续。fork_parent函数解锁被fork_prepare锁住的互斥量。

函数fork_child是child处理器,它将在子进程中被fork调用,在大多数情况中,child处理器需要执行在fork_parent处理器中做过的处理,解锁状态以便子进程能继续运行,它可能也需要执行附加的清除操作。

0 0
原创粉丝点击