This chapter describes three patterns and one idiom that simplify locking in concurrent systems: Scoped Locking, Strategized Locking, Thread-Safe Interface, and Double-Checked Locking Optimization.
Developing multi-threaded applications is harder than developing sequential programs because an object can be manipulated concurrently by multiple threads, which may corrupt its internal state.
Synchronization mechanisms, such as mutexes or semaphores [McK95]
, can help
ensure objects are serialized correctly. This chapter presents three patterns and an idiom that provide solutions to problems related to synchronizing concurrent objects.
The first idiom and pattern address lock acquisition/release and locking strategies:
C++ idiom ensures that a lock is acquired automatically when control enters a scope and released automatically when control leaves the scope, regardless of the return path from the scope.
design pattern is a specialization of the Strategy pattern [GoF95] that parameterizes the synchronization mechanisms used in a component that protect its critical sections from concurrent access.
When implemented in C++ the Strategized Locking pattern often applies the Scoped Locking idiom. The other two patterns help improve the robustness and efficiency of synchronization mechanisms:
design pattern minimizes locking overhead and ensures that intra-component method calls do not incur `self-deadlock' by trying to reacquire a lock that a component already holds.
Double-Checked Locking Optimization
design pattern reduces contention and synchronization overhead whenever critical sections of code must acquire locks in a thread-safe manner only once during program execution.
All four patterns and idioms can be used to enhance the implementations of the Concurrency patterns presented in Chapter 5.
Other patterns related to synchronization include Code Locking and Data Locking [McK95], Reader/Writer Locking [McK95] [Lea99a], Object Synchronizer [SPM99], as well as Balking and Guarded Suspension [Lea99a].