3.2.2 Suspending Thread Execution

A thread can suspend and resume the execution of another thread using the SuspendThread and ResumeThread functions. To do this the controlling thread must have an open handle with THREAD_SUSPEND_RESUME access to the other thread. While a thread is suspended, it is not scheduled for time on the processor. A thread can suspend itself, but of course, it cannot resume by itself. SuspendThread is not particularly useful for synchronization, since it does not control the point in the code at which the thread's execution is suspended. You might want to suspend a thread in a situation where you are confirming a user's input that would terminate the work of the thread. If confirmed, the thread could be terminated ; otherwise, it could be resumed. The creation flags argument to CreateThread allows a thread to be created in a suspended state. This means that the new thread will not begin to execute until ResumeThread is called with a handle to the suspended thread. This can be useful if you want to initialize the thread's state before it begins execution. The example later in this chapter uses this method to modify the thread's priority before it can execute. Suspending a thread at creation can be useful for one-time synchronization, since ResumeThread can be called with the assurance that the suspended thread will begin executing at the starting point of its code.

A thread can temporarily suspend its own execution for a specified interval by calling the Sleep function. This is useful particularly in cases where the thread is responding to user interaction, since it can delay execution long enough to allow the user to observe the results of their actions. During the sleep interval, the thread is not scheduled for time on the processor.