Coder Perfect

Forking vs Threading

Problem

I’ve used threading before in my apps and am familiar with the basics, but I only recently learned about forks in an operating system lecture (). It’s similar to threading in that way.

I googled the differences between them and discovered the following:

However, I still have several unanswered questions.

Asked by Rushabh RajeshKumar Padalia

Solution #1

The most significant distinction between forking and threading is one of operating system architecture. Forking was promoted on Unix systems because it was an uncomplicated, straightforward approach that best answered the mainframe and server type requirements back when Unix was designed. When Microsoft rebuilt the NT kernel from the ground up, it put a greater emphasis on the threading paradigm. As a result, there is still a noticeable difference between Unix systems and Windows systems, with Unix systems being more efficient with forking and Windows being more efficient with threads. This is most evident in Apache, which employs the prefork method on Unix and thread pooling on Windows.

In response to your specific inquiries:

On a Unix system, if you need to do more than merely instantiate a worker, or if you want the implicit security sandboxing of different processes,

Utilize fork if the child will perform the same task as the parent and will use the same code. Use threads for smaller subtasks. Use neither for independent external processes; instead, call them with the appropriate API methods.

I’m not sure, but I believe that duplicating a process with a large number of subthreads is computationally expensive.

This is incorrect; forking produces a new process that can use all of the functionality accessible to processes in the OS task scheduler.

Answered by Niels Keurentjes

Solution #2

A forked process is referred to as heavy-weight, whereas a threaded process is referred to as light-weight.

The differences between them are as follows:

Answered by Selvaperumal

Solution #3

As you’ve noticed, fork() creates a new clone of the process. The exec() call, which frequently follows, is not stated above. As a result, fork()/exec() is the traditional method of generating a new process from an existing one, as it replaces the existing process with a new one (a new executable).

For example, that’s how your shell will run a command from the command line. The shell forks and then executes ls once you specify your process (let’s say ls).

It’s important to note that this isn’t the same as threading. Threading allows you to run numerous lines of code within a single process. The term “forking” refers to the process of establishing new ones.

Answered by Brian Agnew

Post is based on https://stackoverflow.com/questions/16354460/forking-vs-threading