原子代码段,Critical section 使用方法 使用方法 Example Code For Critical Sections with Win32 API /* Sample C/C++, Windows, link to kernel32.dll */ //在windows平台下,调用了kernel32.dll的windows API函数 #include <windows.h> static CRITICAL_SECTION cs; /* This is the critical section object -- once initialized,it cannot be moved in memory */ /* If you program in OOP, declare this in your class */ /* Initialize the critical section before entering multi-threaded context. */ //在你进入多线程调用前,需要调用这个函数进行初始化 InitializeCriticalSection(&cs); void f() { /* Enter the critical section -- other threads are locked out */ //进入原子代码段,不可分割代码段,锁死其他线程,使其他线程不会进入。 EnterCriticalSection(&cs); /* Do some thread-safe processing! */ //在这段代码中线程不会中断直到执行完毕 /* Leave the critical section -- other threads can now EnterCriticalSection() */ //离开原子代码段。其他线程才个进入 LeaveCriticalSection(&cs); } /* Release system object when all finished -- usually at the end of the cleanup code */ //释放系统对象。一般用在代码结束的时候。 DeleteCriticalSection(&cs); 这段代码是保护C++多线程安全性的代码。 在C++多线程异步调用过程中可保证不会出现脏读和多线程冲突的产生。 本文来自网络