zoukankan      html  css  js  c++  java
  • 多线程之间通讯方式

    一、全局变量

      注意:必须是一个进程底下的线程才可以使用全局变量,因为同一个进程底线的所有线程共享地址进程的地址空间。

    二、发消息

    //消息定义
    #define MY_THREAD_MSG (WM_USER + 100)
    
    //接收
    UINT PrintFunction(LPVOID pParam)
    {
        MSG msg = { 0 };
        while (GetMessage(&msg,0,0,0))
        {
            switch (msg.message)
            {
            case MY_THREAD_MSG:
            {
                int num = msg.wParam;
                CString strText;
                strText.Format(_T("%d
    "), num);
                OutputDebugString(strText);
                break;
            }
            }
        }
    
        return 0;
    }
    
    //发送
    UINT WriteFunction(LPVOID pParam)
    {
        int num = 0;
        DWORD dwPrintThreadId = (DWORD)pParam;
        while (true)
        {
            PostThreadMessage(dwPrintThreadId, MY_THREAD_MSG, (WPARAM)num++, NULL);
            Sleep(100);
        }
    
        return 0;
    }
    
    //创建发送和接受线程
    void CMFCApplication1Dlg::OnBnClickedOk()
    {
        CWinThread* pThreadPrint = AfxBeginThread(PrintFunction, this, THREAD_PRIORITY_TIME_CRITICAL, NULL);
    
        CWinThread* pThreadWrite = AfxBeginThread(WriteFunction, (LPVOID)pThreadPrint->m_nThreadID, THREAD_PRIORITY_IDLE, NULL);
    }
    View Code

    三、在新界面线程中调用AfxGetApp();获取到的是程序主线程的指针。

    111
  • 相关阅读:
    LeetCode Power of Three
    LeetCode Nim Game
    LeetCode,ugly number
    LeetCode Binary Tree Paths
    LeetCode Word Pattern
    LeetCode Bulls and Cows
    LeeCode Odd Even Linked List
    LeetCode twoSum
    549. Binary Tree Longest Consecutive Sequence II
    113. Path Sum II
  • 原文地址:https://www.cnblogs.com/zwj-199306231519/p/14725019.html
Copyright © 2011-2022 走看看