多线程之间通讯方式

一、全局变量

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

二、发消息

//消息定义
#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\n"), 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();获取到的是程序主线程的指针。

posted @ 2021-05-01 23:03  zwj鹿港小镇  阅读(213)  评论(0编辑  收藏  举报