zoukankan      html  css  js  c++  java
  • 多线程实现消息通信

    多线程实现消息通信

    在测试学习线程创建及通信过程中,测试多种方式,感觉此种较为简单易懂实用

    #include <stdio.h>
    #include <windows.h>
    
    struct info
    {
        HWND hWnd;
        DWORD dwThreadId;
        char* thing;
    };
    
    DWORD  WINAPI ThreadFun(LPVOID lpParam);// Main Thread
    DWORD  WINAPI Thread1(LPVOID lpParam);    // Sub Thread
    
    int main()
    {
        info Info;
        char th[] = "somthing";
        Info.hWnd = GetActiveWindow();//GetSafeHwnd(); // get current HWND
        Info.thing = th;
        DWORD dwThreadID;
        HANDLE hThread = CreateThread(NULL,0, ThreadFun,&Info, NULL,&dwThreadID);
        Info.dwThreadId = dwThreadID;
        WaitForSingleObject(hThread, INFINITE);
        CloseHandle(hThread);
        HANDLE hCurrentProc = GetCurrentProcess();
        printf("%08X %08X
    ", hThread, hCurrentProc);
        
        return 0;
    }
    
    DWORD  WINAPI ThreadFun(LPVOID lpParam)
    {
        info* Info = (info*)lpParam;//传递的消息结构体
        printf("Thread Start!!!!!
    ");
        
        printf("ThreadID %d
    ", Info->dwThreadId);//
        MSG msg;
        
        info mInfo;
        mInfo.dwThreadId = GetCurrentThreadId();
        
        HANDLE hThread1 = CreateThread(NULL,0, Thread1, &mInfo, NULL, NULL);
        printf("SomeThing %s
    ", Info->thing);
    
    //主线程实现消息检测循环,当接收退出信息退出循环
    while(1) { PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); if(msg.message == WM_QUIT) { printf(" Get message(Quit) from Thread1 "); CloseHandle(hThread1); break; } } printf("Thread Over! "); return 0; } //子线程 DWORD WINAPI Thread1(LPVOID lpParam) { info* Info = (info*)lpParam; printf(" Thread1 Start!!!!! "); printf(" This ThreadID(%d) is MainThreadID!!!!! ", Info->dwThreadId); printf(" Thread1ID %d ", GetCurrentThreadId()); int ret = PostThreadMessage(Info->dwThreadId, WM_QUIT, NULL, NULL); if(ret == ERROR_INVALID_THREAD_ID) printf(" postthreadmessage Fail!!!!! "); else printf(" ret: 0x%08x ", ret); return 0; }
    ded3
  • 相关阅读:
    数组初始化 和 vector初始化
    剑指offer42 左旋转字符串
    k sum(lintcode)
    背包问题2 (lintcode)
    92.背包问题(lintcode)
    72. Edit Distance
    79 最长公共子串 (lintcode)
    77 最长公共子序列 (lintcode)
    132. Palindrome Partitioning II
    Mysql经常使用函数汇总
  • 原文地址:https://www.cnblogs.com/dedeblog/p/6134395.html
Copyright © 2011-2022 走看看