linux下多線程中的fork介紹
問題提出:
回想一下:當一個程序只有主線程的時候調用fork,此時fork會創(chuàng)建出的子進程也會只有一條線程;
那要是把fork放入多線程的程序中呢?
我們來試驗下:
情況(1)fork在創(chuàng)建子線程之前
代碼:
#include <stdio.h> #include <pthread.h> #include <unistd.h> void* pthread_fun(void* arg) { printf("fun = %d\n", getpid()); pthread_exit(NULL); } int main() { fork(); pthread_t id; pthread_create(&id, NULL, pthread_fun, NULL); printf("main_pid = %d\n", getpid()); pthread_join(id, NULL); return 0; }
結果:fork出的子進程也會創(chuàng)建自己的子線程(兩個進程:四個線程
)
情況(2)fork在創(chuàng)建子線程之后
代碼:
#include <stdio.h> #include <pthread.h> #include <unistd.h> void* pthread_fun(void* arg) { printf("fun = %d\n", getpid()); pthread_exit(NULL); } int main() { pthread_t id; pthread_create(&id, NULL, pthread_fun, NULL); fork(); printf("main_pid = %d\n", getpid()); pthread_join(id, NULL); return 0; }
結果:創(chuàng)建子線程之后,再創(chuàng)建子進程,此時fork的子進程只會執(zhí)行fork之后的代碼(兩個進程:三個線程
)
情況(3)子線程中的fork
代碼:
#include <stdio.h> #include <pthread.h> #include <unistd.h> void* pthread_fun(void* arg) { fork(); printf("fun = %d\n", getpid()); pthread_exit(NULL); } int main() { pthread_t id; pthread_create(&id, NULL, pthread_fun, NULL); printf("main_pid = %d\n", getpid()); pthread_join(id, NULL); return 0; }
結果:
結論:
fork處于哪個線程中,fork后創(chuàng)建的子進程將以該線程作為自己的主線程,并且執(zhí)行該線程之后的代碼
到此這篇關于linux下多線程中的fork介紹的文章就介紹到這了,更多相關linux多線程fork內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決Linux可執(zhí)行文件目錄下明明存在*.so文件,但卻提示找不到
這篇文章主要介紹了解決Linux可執(zhí)行文件目錄下明明存在*.so文件,但卻提示找不到問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11