Rajinder Yadav - C++ Windows Development Tools & Resources :Design, Code, Test, Debug

Thread Concepts, by Rajinder Yadav
March 5, 2002

Thread Models

There are two type of threading models in uses today, they are preemptive model and the time-slice model. You don't need to know them in order to use threads, but it helps if you understand them so you can plan a good design for your threaded programs. All threads have a priority level associated with them, usually when one thread is created, the created thread is given the same priority at the one that created it. Thread priority plays an important role in both thread models.

Each model has it's own scheduling policy, preemptive threads work in a cooperative manner, giving up the CPU when they've completed a task. A thread with the same priority level or greater can 'preempt' the current running thread to gain the CPU. In a time-slice model, each thread is alloted a time quota that is determined by it's priority level, in this model each thread runs until it has used up it time quota.

The scheduler determine when to swap out a running thread and replace it with a thread from the waiting queue. When a thread swap happens, we say that a context-switch has occurred, this is one of the most expensive operation of running a thread. When a context-switch occurs, the register values, stack frame and the instruction pointer(IP) for the running thread have to be saved, next the register values, stack frame and IP for the other thread need to be initialized before the thread can being running. As you can well imagine this eats up a lot of CPU cycles.

The other most expensive operation is thread creation, so it's not wise to create new threads to do the same job over and over. The best policy is to create the threads that will be required throughout the life-cycle of your program and simply suspend and resume them as needed. Suspended thread in the wait state use up very little memory, no resources and practically zero CPU cycles.

Copyright © 2002 Rajinder Yadav, All Rights Reserved

Home