关于同一线程两次调用EnterCriticalSection的测试
#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; }
本博客注有“转”字样的为转载文章,其余为本人原创文章,转载请务必注明出处或保存此段。c++/lua/windows逆向交流群:69148232