Bemærk
Adgang til denne side kræver godkendelse. Du kan prøve at logge på eller ændre mapper.
Adgang til denne side kræver godkendelse. Du kan prøve at ændre mapper.
To synchronize access to a resource, use one of the synchronization objects in one of the wait functions. The state of a synchronization object is either signaled or nonsignaled. The wait functions allow a thread to block its own execution until a specified nonsignaled object is set to the signaled state. For more information, see Interprocess Synchronization.
Choosing the right synchronization primitive
| Primitive | Scope | Performance | Reentrant | When to use |
|---|---|---|---|---|
| Slim Reader/Writer (SRW) Lock | Single process | Fast (typically user-mode; may enter kernel under contention) | No | Default choice for reader-heavy workloads in modern code. Smallest memory footprint (pointer-sized). |
| Critical Section | Single process | Fast (spins then kernel wait) | Yes | Use when you need reentrant/recursive locking within one process. Slightly larger than SRW. |
| Mutex | Cross-process (named) | Slower (always kernel object) | Yes | Required for synchronization between processes via a named mutex. Also useful with WaitForMultipleObjects. |
| Semaphore | Cross-process (named) | Kernel object | N/A | Limits concurrent access to a resource pool (e.g., connection pool of N items). |
| Event | Cross-process (named) | Kernel object | N/A | Signaling between threads/processes. Use for "something happened" notifications, not for protecting data. |
C++ std::mutex / std::shared_mutex |
Single process | Implementation-defined | No | Preferred for portable C++ code and RAII. Use when you don't need Win32 wait APIs or cross-process synchronization. |
Note
SRW locks vs Critical Sections: For new code that doesn't require recursive locking, prefer SRW locks (AcquireSRWLockExclusive/AcquireSRWLockShared). They are smaller, faster, and support reader/writer semantics. Critical sections are still appropriate when you need reentrant (recursive) acquisition by the same thread.
Important
Common mistake: Using a Mutex for intra-process synchronization when a Critical Section or SRW lock would suffice. Mutexes always involve a kernel mode transition, making them significantly slower for high-frequency operations within a single process.
The following are other synchronization mechanisms:
- overlapped input and output
- asynchronous procedure calls
- critical section objects
- condition variables
- slim reader/writer locks
- one-time initialization
- interlocked variable access
- interlocked singly linked lists
- timer queues
- the MemoryBarrier macro
For additional information on synchronization, see Synchronization and Multiprocessor Issues.