015 CONTEXT 線程安全上鎖 代碼實現
阿新 • • 發佈:2017-06-24
安全 windows.h lpar hand 代碼實現 void infinite tip process
#define UNICODE #include <stdio.h> #include <tchar.h> #include <windows.h> #include <process.h> BOOL bUseing = FALSE; unsigned int __stdcall ThreadRun(void* lParam) { int nNum = 0; while(true) { if(!bUseing) { bUseing = TRUE; //上鎖 printf("ThreadRun:%d\r\n",nNum++); //確保使用完成後才被暫停 bUseing = FALSE; } } } unsigned int __stdcall ThreadMonitor(void* lParam) { HANDLE hThread = (HANDLE)(lParam); while(true) { CONTEXT context; context.ContextFlags = CONTEXT_ALL; //暫停線程 SuspendThread(hThread); GetThreadContext(hThread,&context); if(!bUseing) { bUseing = TRUE; //上鎖 printf("EAX:0x%x ESP:0X%x EIP:0x%x\r\n",context.Eax,context.Esp,context.Eip); bUseing = FALSE; } //開始線程 ResumeThread(hThread); } } int main() { HANDLE hThread[2]; hThread[0] = (HANDLE)_beginthreadex(nullptr,0,ThreadRun,nullptr,0,nullptr); hThread[1] = (HANDLE)_beginthreadex(nullptr,0,ThreadMonitor,hThread[0],0,nullptr); WaitForMultipleObjects(sizeof(hThread)/sizeof(HANDLE), hThread,TRUE, INFINITE); for(int i = 0; i<sizeof(hThread)/sizeof(HANDLE);++i) { CloseHandle(hThread[i]); } return 0; }
015 CONTEXT 線程安全上鎖 代碼實現