Question:Recall that when a program has only one main thread and fork is called, the child process created by fork will also have only one thread; What if we put fork into a multi-threaded program? Let's try it out: Case (1) fork before creating a child threadCode: #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; } Result: The forked child process will also create its own child thread ( Case (2) fork after creating a child threadCode: #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; } Result: After creating a child thread, a child process is created. At this time, the fork child process will only execute the code after fork ( Case (3) fork in child threadCode: #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; } result: in conclusion:In which thread is fork, the child process created after fork will use this thread as its main thread and execute the code after this thread This is the end of this article about fork in multi-threading under Linux. For more relevant Linux multi-threading fork content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: What are inline elements and block elements?
>>: Detailed explanation of common usage of pseudo-classes before and after in CSS3
Let’s start the discussion from a common question...
Table of contents What is Routing Basic use of pu...
Overview The builder pattern is a relatively simp...
MySQL full text search Chinese solution Recently,...
Using abbreviations can help reduce the size of yo...
Preface The reduce() method receives a function a...
Mine is: <!DOCTYPE html> Blog Garden: <!...
Introduction to the usage of MySQL keyword Distin...
Optimistic Locking Optimistic locking is mostly i...
I have encountered many centering problems recent...
This article records the detailed process of down...
Download opencv.zip Install the dependencies ahea...
Before introducing the GROUP BY and HAVING clause...
Table of contents 1. Array deduplication 2. Dedup...
1. Install vue-cli npm i @vue/cli -g 2. Create a ...