Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 792
danmine Avatar asked Mar 06 '09 06:03

danmine


2 Answers

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.

like image 181
Frederick The Fool Avatar answered Oct 01 '22 20:10

Frederick The Fool


Well apart from advantages of using thread over process, like:

Advantages:

  • Much quicker to create a thread than a process.
  • Much quicker to switch between threads than to switch between processes.
  • Threads share data easily

Consider few disadvantages too:

  • No security between threads.
  • One thread can stomp on another thread's data.
  • If one thread blocks, all threads in task block.

As to the important part of your question "When should I use a thread?"

Well you should consider few facts that a threads should not alter the semantics of a program. They simply change the timing of operations. As a result, they are almost always used as an elegant solution to performance related problems. Here are some examples of situations where you might use threads:

  • Doing lengthy processing: When a windows application is calculating it cannot process any more messages. As a result, the display cannot be updated.
  • Doing background processing: Some tasks may not be time critical, but need to execute continuously.
  • Doing I/O work: I/O to disk or to network can have unpredictable delays. Threads allow you to ensure that I/O latency does not delay unrelated parts of your application.
like image 29
simplyharsh Avatar answered Oct 01 '22 21:10

simplyharsh