Threads

A thread describes a path of execution within a process. Every time the OS creates a new process, it also creates at least one thread. The purpose of creating a thread is to make use of as much of the CPU's time as possible. For example, in many applications, it is useful to create a separate thread to handle printing tasks so that the user can continue to use the application while it is printing.

Each thread shares all of the process's resources, including its address space. Additionally, each thread has a stack, where the linker sets the stack size for all of the threads that are created in a process (/STACK). A thread also contains the state of the CPU registers, known as the "context," and an entry in the execution list of the system scheduler. You can use the GetThreadContext function to retrieve the context of the specified thread and the SetThreadContext function to set the context of the specified thread.

Each thread in a process operates independently. Unless you make the threads visible to each other, they execute individually and are unaware of the other threads in a process. Threads sharing common resources, however, must coordinate their work by using a method of synchronization.

An application starts when the system scheduler gives one of its threads execution control. The system scheduler determines which threads should run and when they should run. Threads of lower priority may have to wait while higher priority threads complete their tasks.

Threads can be in one of the following states: running, suspended, sleeping, blocked, or terminated. When all threads are in the blocked state, Windows CE enters the suspended mode, which stops the CPU from executing instructions and consuming power. To conserve power, be sure to use synchronization objects to block threads that are waiting, instead of creating a thread that polls for status, such as the PeekMessage function.