日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LInux线程——多线程与fork之间的问题

發布時間:2024/4/17 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LInux线程——多线程与fork之间的问题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.多線程中某個線程調用 fork(),子進程會有和父進程相同數量的線程嗎?

1.1fork在創建線程前

pthread_fork1.c代碼:

#include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<assert.h> #include<pthread.h>void* pthread_fun(void* arg) {for(int i = 0; i < 5; i++){printf("pthread_fun:pid = %d\n",getpid());sleep(1);}pthread_exit(NULL); }int main() {pthread_t id;pid_t pid;pid = fork();assert(pid != -1);pthread_create(&id,NULL,pthread_fun,NULL);if(pid == 0){for(int i = 0; i < 5; i++){printf("fork:pid = %d\n",getpid());sleep(1);}}else{for(int i = 0; i < 5; i++){printf("main:pid = %d\n",getpid());sleep(1);}}pthread_join(id,NULL);exit(0); }

運行情況:

發現fork()后的子進程也創建了線程。

1.2在創建線程后fork

pthread_fork2.c代碼:

#include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<assert.h> #include<pthread.h>void* pthread_fun(void* arg) {for(int i = 0; i < 5; i++){printf("pthread_fun:pid = %d\n",getpid());sleep(1);}pthread_exit(NULL); }int main() {pthread_t id;pthread_create(&id,NULL,pthread_fun,NULL);pid_t pid;pid = fork();assert(pid != -1);if(pid == 0){for(int i = 0; i < 5; i++){printf("fork:pid = %d\n",getpid());sleep(1);}}else{for(int i = 0; i < 5; i++){printf("main:pid = %d\n",getpid());sleep(1);}}pthread_join(id,NULL);exit(0); }

運行結果:
發現只創建了一條,是父進程創建的,子進程并沒有創建線程。

1.3在線程函數里面fork

pthread_fork3.c代碼:

#include<stdio.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #include<assert.h> #include<pthread.h>void* pthread_fun(void* arg) {pid_t pid;pid = fork();assert(pid != -1);for(int i = 0; i < 5; i++){printf("pthread_fun:pid = %d\n",getpid());sleep(1);}pthread_exit(NULL); }int main() {pthread_t id;pthread_create(&id,NULL,pthread_fun,NULL);for(int i = 0; i < 5; i++){printf("main:pid = %d\n",getpid());sleep(1);}pthread_join(id,NULL);exit(0); }

運行結果:

發現,只是線程函數多了一個而已 。

總結:進程fork后,fork所在的那一條線程會會繼續執行。如果fork()之后,子進程繼續向下執行,有創建線程的話,子進程會創建線程;如果fork()之后,子進程繼續向下執行,沒有創建線程的話,子進程就不會創建線程;fork在線程函數里的話,只會把線程復制一份。
不管怎么樣,fork都復制了整個進程,但是只啟用了它所在的那個執行路徑,如果它所在的那個執行路徑fork后有創建線程的話,子進程會創建線程;如果它所在的那個執行路徑fork后沒有創建線程而在fork之前有創建線程的話,那么fork不會啟用fork之前創建的線程,只會啟用當前所在線程,繼續執行下去。

2.父進程被加鎖的互斥鎖 fork 后在子進程中是否已經加鎖?

答:父進程的鎖會被復制到子進程中,fork復制時候,父進程的鎖是什么狀態,fork的進程的鎖就是什么狀態。

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的LInux线程——多线程与fork之间的问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。