#include "stdafx.h" #include <iostream> using namespace std; #include <windows.h> #include <process.h> CRITICAL_SECTION cs; //1.测试同一线程两次EnterCriticalSection会不会阻塞 //答案:不会 /* int _tmain(int argc, _TCHAR* argv[]) { InitializeCriticalSection(&cs); EnterCriticalSection(&cs); EnterCriticalSection(&cs); for(int i = 0;i < 20;i++) { cout<<"MainThread:"<<i<<endl; Sleep(1000); } LeaveCriticalSection(&cs); DeleteCriticalSection(&cs); system("pause"); return 0; } */ //2.测试同一线程两次EnterCriticalSection,调用一次LeaveCriticalSection 另一个线程是否可以以EnterCriticalSection //答案:不可以 两次EnterCriticalSection 必须调用 LeaveCriticalSection两次 unsigned __stdcall ThreadPorc ( void * ) { for(int i = 0;i<20;i++) { EnterCriticalSection(&cs); cout<<"线程2进入"<<endl; break; LeaveCriticalSection(&cs); Sleep(1000); } return 0; } int _tmain(int argc, _TCHAR* argv[]) { InitializeCriticalSection(&cs); EnterCriticalSection(&cs); EnterCriticalSection(&cs); _beginthreadex(NULL,0,ThreadPorc,NULL,0,NULL); for(int i = 0;i < 20;i++) { if(i == 10) { LeaveCriticalSection(&cs); } cout<<"MainThread:"<<i<<endl; Sleep(1000); } LeaveCriticalSection(&cs); Sleep(5000); DeleteCriticalSection(&cs); system("pause"); return 0; }