Using Critical Section Objects The following example shows how a thread initializes, enters, and leaves a critical section. As with the mutex example (see Using Mutex Objects), this example uses structured exception-handling syntax to ensure that the thread calls the LeaveCriticalSection function to release its ownership of the critical section object. // Global variable CRITICAL_SECTION CriticalSection; void main() { ... // Initialize the critical section one time only. InitializeCriticalSection(&CriticalSection); ... // Release resources used by the critical section object. DeleteCriticalSection(&CriticalSection) }DWORD WINAPI ThreadProc( LPVOID lpParameter ) { ... // Request ownership of the critical section. __try { EnterCriticalSection(&CriticalSection); // Access the shared resource. } __finally { // Release ownership of the critical section. LeaveCriticalSection(&CriticalSection); } ...} csdn上面的sample,就是try catch
在需要同步时,在{}里生成类的对象
The following example shows how a thread initializes, enters, and leaves a critical section. As with the mutex example (see Using Mutex Objects), this example uses structured exception-handling syntax to ensure that the thread calls the LeaveCriticalSection function to release its ownership of the critical section object. // Global variable
CRITICAL_SECTION CriticalSection; void main()
{
... // Initialize the critical section one time only.
InitializeCriticalSection(&CriticalSection); ... // Release resources used by the critical section object.
DeleteCriticalSection(&CriticalSection)
}DWORD WINAPI ThreadProc( LPVOID lpParameter )
{
... // Request ownership of the critical section.
__try
{
EnterCriticalSection(&CriticalSection); // Access the shared resource.
}
__finally
{
// Release ownership of the critical section.
LeaveCriticalSection(&CriticalSection);
} ...}
csdn上面的sample,就是try catch
配对使用。中间使用break,return时一定要注意