In a multitasking environment it is essential to coordinate the
execution of multiple threads in one or more processes. In a multitasking environment
where thread execution is conceptually concurrent (actually concurrent in Windows NT SMP
systems) programmers must be careful to coordinate the execution of multiple threads in
one or more processes.
The scheduler may pre-empt a thread at any time, including while it is in the middle of
accessing a data area, device, or section of non-reentrant code. Such serially
reusable resources (SRRs) should only be used by one thread at a time, otherwise
their data may become corrupted or a deadlock may occur. Also, it is sometimes important
to coordinate threads; one thread may need to wait for another to complete an action
before carrying out its task. The work of ensuring that only one thread at a time accesses
an SRR is known as arbitration or mutual exclusion, while
the coordination of threads is referred to as synchronization
The Win32 synchronization objects are essentially flags maintained by the operating
system, which enable threads to signal each other in order to synchronize their activities
and to protect non-reentrant code and resources by providing mutual exclusion.
This chapter looks at the four different types of synchronization object provided by
Win32, and demonstrates how each kind is used.
Objectives
When you have completed this chapter, you should be able to:
- Explain why thread synchronization is necessary.
- Make an appropriate choice for the method of synchronizing threads.
- Use Event objects to signal that a significant event has taken place.
- Use Semaphore objects to act as a resource gate.
- Use Mutex objects and Critical Section objects to provide mutual exclusion.
- Synchronize threads using one or more Win32 objects.
Avoid thread deadlock and race conditions.