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

Solution 1:

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.

Solution 2:

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.

Solution 3:

I assume you already know you need a thread or a process, so I'd say the main reason to pick one over the other would be data sharing.

Use of a process means you also need Inter Process Communication (IPC) to get data in and out of the process. This is a good thing if the process is to be isolated though.