线程中fork函数的使用

来源:互联网 发布:mysql synonym 编辑:程序博客网 时间:2024/05/22 12:50

一、线程中fork函数的是使用(线程与进程的结合)

线程中调用fork函数创建子进程,子进程仅仅执行调用fork函数的这个线程,其他的线程不会被调用。

画图解释:

示例代码:

#include <stdio.h>#include <stdlib.h>#include <assert.h>#include <string.h>#include <unistd.h>#include <pthread.h>//线程中fork函数的使用//在主线程中fork,再次验证只执行fork函数创建的这个线程void *fun(void*arg){    while(1)    {        sleep(1);        printf("pthread(%d)\n",getpid());    }}void main(){    fork();    while(1)    {        sleep(1);        printf("main(%d)\n",getpid());    }}//在函数线程中fork/*void *fun(void *arg){    if(fork()==0)    {        printf("child(%d)\n",getpid());    }    else    {        printf("pthread(%d)\n",getpid());    }}void main(){    pthread_t th;    int res=pthread_create(&th,NULL,fun,NULL);    assert(res==0);    while(1)    {        sleep(1);        printf("main(%d)\n",getpid());    }}在主线程中fork打印结果:        main(3239)        main(3240)        ...在函数线程中fork打印结果:        pthread(3286)        child(3288)        main(3286)        main(3286)        ...
原创粉丝点击