When to choose multithreading or multiprocessing?

2019-03-29 00:55发布

问题:

I've never done something on concurrent programming.What I know about them is only from OS books.

And I met this question on an interview today. I wonder if anybody can give me an intuitive

explanation on multithread and multiprocess and when to choose them. Or,maybe you can

recommend me some books or links with actual examples. And I want to read source codes of

open-source project(c/c++) with conccurent programming,Hope that you can recommend one .

Thanks very much for your any help.

回答1:

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.