首页 > 代码库 > 015 CONTEXT 线程安全上锁 代码实现

015 CONTEXT 线程安全上锁 代码实现

#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 线程安全上锁 代码实现