C++ Thread Sync: EnterCriticalSection

In C++, EnterCriticalSection is a critical section locking mechanism provided by the Windows API. It is used to restrict access to shared resources to ensure that only one thread can access the resource at any given time.

Here are the basic steps for using EnterCriticalSection:

  1. First, define a CRITICAL_SECTION object to represent the critical section.
CRITICAL_SECTION cs;
  1. Use the EnterCriticalSection function to lock the critical section in places where protection of shared resources is required.
EnterCriticalSection(&cs);
  1. Perform operations on shared resources.
  2. Release the critical section using the LeaveCriticalSection function.
LeaveCriticalSection(&cs);

The complete example code is shown below:

#include <Windows.h>
#include <iostream>

CRITICAL_SECTION cs;

int main() {
    // 初始化临界区
    InitializeCriticalSection(&cs);

    // 进入临界区
    EnterCriticalSection(&cs);

    // 访问共享资源
    std::cout << "Accessing shared resource" << std::endl;

    // 离开临界区
    LeaveCriticalSection(&cs);

    // 销毁临界区
    DeleteCriticalSection(&cs);

    return 0;
}

Please note that EnterCriticalSection and LeaveCriticalSection must be used in pairs and the operations on shared resources should be performed within the critical section. Also, it is necessary to call DeleteCriticalSection before the program ends to destroy the critical section.

bannerAds