Asynchronous Procedure Calls
One major objection to ThreeStage.c (Program 10-5), as it is currently written, is the use of TerminateThread at the end to end the transmitter and receiver threads. A code comment asks if there is a cleaner way to terminate threads so they can shut down in an orderly way and free resources.Another open problem is that there is no general method (other than TerminateThread) to signal, or cause an action in, a specific thread. Events signal one thread waiting on an auto-reset event or all the threads waiting on a manual-reset event, but there is no way to assure that a particular thread is signaled. The solution used so far is simply to wake up all the waiting threads so they can individually determine whether it is time to proceed. An alternative solution, which is occasionally used, is to assign events to specific threads so that the signaling thread can determine which event to pulse or set.APCs provide a solution to both of these problems. The sequence of events is as follows, where the boss thread needs to control a cooperating worker or target thread.
- The boss thread specifies an APC routine to the target thread by queuing the APC to the target. More than one APC can be queued to a specific thread.
- The target thread enters an alertable wait state indicating that the thread can safely execute the APC. The order of these first two steps is irrelevant so there is no concern here with race conditions.
- A thread in an alertable wait state will execute all queued APCs.
- An APC can carry out any appropriate action, such as freeing resources or raising an exception. In this way, the boss thread can cause an exception to occur in the target, although the exception will not occur until the target has entered an alertable state.
APC execution is asynchronous in the sense that a boss thread can queue an APC to a target at any time, but the execution is synchronous in the sense that it can occur only when the target thread enters an alertable wait state.Alertable wait states will be discussed again in Chapter 14, which covers asynchronous I/O.The following sections describe the required functions and illustrate their use with another variation of the ThreeStage program. On the book's Web site, the source file is THReeStageCancel.c and the project to build this version is ThreeStageCancel.
