When to choose multithreading or multiprocessing? [closed] When to choose multithreading or multiprocessing? [closed] multithreading multithreading

When to choose multithreading or multiprocessing? [closed]


Multithread:

  • Execution is split among threads; on some operating systems these threads are lighter than processes; on Linux, instead, they are internally implemented using the same data structures.
  • Threads share memory, so global shared data structures must be protected through mutual exclusion mechanisms (e.g., semaphores, mutex, condition variables, etc.)
  • On Linux, the pthread library (which stands for "POSIX threads") provides multithread support at user-level; threads are created using pthread_create(); this library can be used in normal C/C++ programs by compiling with the -pthread option.

Multiprocess:

  • Execution is split among processes
  • Processes traditionally do not share memory; on Linux, however, processes can also share memory through suitable system calls
  • On POSIX systems (e.g., Linux), processes are created through the fork() system call: a process (called "parent") can create ("fork") another process (called "child"). C/C++ program do not need to be linked to any external library to call fork().
  • Data is usually exchanged through message passing mechanisms (e.g., pipes, fifos and sockets)

The decision between using multithread or multiprocess usually depends on two factors:

  1. If you need data shared among different execution entities. Message passing mechanisms are less fast and flexible than shared memory. Therefore, in some cases, it is better to use threads instead of processes.
  2. Reliability: multiprocess applications are usually more reliable because the crash of a process does not affect the other processes.

A final note: very complex applications can have both multithread and multiprocess to accomplish the needs of particular parts of the software.