Alex Rivera | Logout

Why should I use a thread vs. using a process?

Asked 2009-03-06T06:02:10.070
65

Separating different parts of a program into different processes seems (to me) to make a more elegant program than just threading everything. In what scenario would it make sense to make things run on a thread vs. separating the program into different processes? When should I use a thread?


Edit

Anything on how (or if) they act differently with single-core and multi-core would also be helpful.

Edit
Report

2 Answers

97

You'd prefer multiple threads over multiple processes for two reasons:

  1. Inter-thread communication (sharing data etc.) is significantly simpler to program than inter-process communication.
  2. Context switches between threads are faster than between processes. That is, it's quicker for the OS to stop one thread and start running another than do the same with two processes.

Example:

Applications with GUIs typically use one thread for the GUI and others for background computation. The spellchecker in MS Office, for example, is a separate thread from the one running the Office user interface. In such applications, using multiple processes instead would result in slower performance and code that's tough to write and maintain.

answered 2009-03-06T06:05:59.360
7

You sure don't sound like a newbie. It's an excellent observation that processes are, in many ways, more elegant. Threads are basically an optimization to avoid too many transitions or too much communication between memory spaces.

Superficially using threads may also seem like it makes your program easier to read and write, because you can share variables and memory between the threads freely. In practice, doing that requires very careful attention to avoid race conditions or deadlocks.

There are operating-system kernels (most notably L4) that try very hard to improve the efficiency of inter-process communication. For such systems one could probably make a convincing argument that threads are pointless.

answered 2009-03-06T06:45:37.517

Your Answer