zoukankan      html  css  js  c++  java
  • 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
    ",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
    ",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;
    }

  • 相关阅读:
    为html瘦身的pythonl函数
    python字符编码演示三则
    爬虫任务队列方案以及性能测试
    从一道动态规划到卡特兰数
    LeetCode 24 JAVA
    链表笔记
    KMP 算法
    LeetCode 有效数独 JAVA
    Leetcode 139 单词拆分 JAVA
    Leetcode 845 数组的山脉 JAVA
  • 原文地址:https://www.cnblogs.com/sdk123/p/7072449.html
Copyright © 2011-2022 走看看