Suspending and Resuming Execution
The thread in a threaded runnable can suspend its own execution or can be suspended by another thread. This operation is implemented by the following functions:
• bool RWThread::canSuspendResume(void) const
• bool RWThreadSelf::canSuspendResume(void) const
• unsigned RWThread::suspend()
• void RWThreadSelf::suspend()
• unsigned RWThread::getSuspendCount() const
• unsigned RWThread::resume()
Suspension is an interruption in the execution of a thread. A suspended thread remains ineligible for execution until continued or resumed. Suspension is asynchronous—the suspended thread has no control over where and when it can be suspended. Only threaded runnables can be suspended. This capability is not included in the synchronous runnable classes.
When a threaded runnable is suspended, its execution state is set to RW_THR_SUSPENDED[18]. When the runnable is resumed, its execution state is restored to the state that existed before the suspension occurred[19].
• Any attempt to suspend an inactive, threaded runnable results in an
RWTHRThreadNotActive exception.
• Any attempt to resume a threaded runnable that is not suspended results in an
RWTHRThreadActive exception.
Figure 14 shows the interaction and state changes associated with the suspension process.
To suspend a thread created by a threaded runnable, use the
suspend() function included by the
RWThread handle class. A thread inside a threaded runnable can suspend itself by calling the
RWThreadSelf::suspend() function.
The RWThread::resume() function is used to resume a suspended thread. A suspended thread cannot resume itself.
Using the suspend() and resume() Functions
The suspend() function can be called any number of times without an intervening call to resume(). The threaded runnable object maintains an internal count of the number of times the thread has been suspended. An equal number of calls to resume() must be made before the thread is allowed to continue. Both suspend() and resume() return the suspend-count that existed after the requested operation was performed.
The current suspend-count of a threaded runnable can be queried using the RWThread::getSuspendCount() function.
Deciding Whether Suspension Is Available
Suspension is not supported in all environments. The Threading package uses the macro
RW_THR_HAS_SUSPEND_RESUME to indicate whether the
suspend(),
resume(), and
getSuspendCount() operations are available. If this macro is not defined, the functions throw an
RWTHROperationNotSupported exception. You can also determine whether suspension is supported at run-time by calling the
canSuspendResume() function in the
RWThread and
RWThreadSelf classes.