码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-06-24 10:10:52      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:unsigned   define   ptr   ++   flags   resume   end   com   cts   

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

标签:unsigned   define   ptr   ++   flags   resume   end   com   cts   

原文地址:http://www.cnblogs.com/sdk123/p/7072449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!