Preemptive threads Vs Non Preemptive threads

Alok Save picture Alok Save · Nov 10, 2010 · Viewed 23.9k times · Source

Can someone please explain the difference between preemptive Threading model and Non Preemptive threading model?

As per my understanding:

  • Non Preemptive threading model: Once a thread is started it cannot be stopped or the control cannot be transferred to other threads until the thread has completed its task.
  • Preemptive Threading Model: The runtime is allowed to step in and hand control from one thread to another at any time. Higher priority threads are given precedence over Lower priority threads.

Can someone please:

  1. Explain if the understanding is correct.
  2. Explain the advantages and disadvantages of both models.
  3. An example of when to use what will be really helpful.
  4. If i create a thread in Linux (system v or Pthread) without mentioning any options(are there any??) by default the threading model used is preemptive threading model?

Answer

Jerry Coffin picture Jerry Coffin · Nov 10, 2010
  1. No, your understanding isn't entirely correct. Non-preemptive (aka cooperative) threads typically manually yield control to let other threads run before they finish (though it is up to that thread to call yield() (or whatever) to make that happen.
  2. Preempting threading is simpler. Cooperative threads have less overhead.
  3. Normally use preemptive. If you find your design has a lot of thread-switching overhead, cooperative threads would be a possible optimization. In many (most?) situations, this will be a fairly large investment with minimal payoff though.
  4. Yes, by default you'd get preemptive threading, though if you look around for the CThreads package, it supports cooperative threading. Few enough people (now) want cooperative threads that I'm not sure it's been updated within the last decade though...