Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreaded fork

Tags:

Can fork() function be used to replicate a multithreaded process. And if so, will all threads be exactly the same and if not, why not. If replication can't be done through fork, is there any other function which can do it for me?

like image 893
MetallicPriest Avatar asked May 19 '11 10:05

MetallicPriest


People also ask

What is fork multithreading?

The fork( ) system call creates an exact duplicate of the address space from which it is called, resulting in two address spaces executing the same code. Problems can occur if the forking address space has multiple threads executing at the time of the fork( ).

What is the difference between forking and multi threading?

Multi-threading is both challenging and rewarding. Show activity on this post. Threads are functions run in parallel, fork is a new process with parents inheritance. Threads are good to execute a task in parallel, while forks are independent process, that also are running simultaneously.

Is forking the same as threading?

Threading runs multiple lines of execution intra-process. Forking is a means of creating new processes.

Does fork duplicate all threads?

A fork() duplicates all the threads of a process. The problem with this is that fork() in a process where threads work with external resources may corrupt those resources (e.g., writing duplicate records to a file) because neither thread may know that the fork() has occurred.


2 Answers

After a fork, only one thread is running in the child. This is a POSIX standard requirement. See the top answer to the question fork and existing threads ?.

like image 85
DarkDust Avatar answered Oct 03 '22 00:10

DarkDust


No, the child will only have one thread. Forking a threaded process is not trivial. (See this article Threads and fork(): think twice before mixing them for a good rundown).

I don't know of any way of cloning a process and all its threads, I don't think that's possible on Linux.

like image 39
Mat Avatar answered Oct 02 '22 23:10

Mat