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
1. Basics of Linux Firewall The Linux firewall sy...
Table of contents Use two-way binding data in v-m...
Table of contents Problem Description Rendering T...
Without further ado, I'll go straight to the ...
Table of contents 1. Environment 2. Preparation 3...
Table of contents Preface - Vue Routing 1. The mo...
Why is NULL so often used? (1) Java's null Nu...
1. Key points for early planning of VMware vSpher...
We all know that Docker containers are isolated f...
Table of contents 1. Usage 2. Output results 1.id...
** Detailed graphic instructions for installing y...
Table of contents Intro Nginx Dockerfile New conf...
Table of contents Preface What is DrawCall How do...
They are all web page templates from the foreign ...
This command modifies the data table ff_vod and a...