DEV Community

海前 王
海前 王

Posted on

thread mfc

//#include "stdafx.h"
#include <iostream>
# include <tchar.h>
#include <string>
#include <windows.h>
using namespace std;

HANDLE h_event1 = NULL;
HANDLE h_event2 = NULL;
DWORD WINAPI FunProc1(LPVOID lpParameter);
DWORD WINAPI FunProc2(LPVOID lpParameter);

DWORD WINAPI FunProc1(LPVOID lpParameter)
{
    cout << "线程1开始运行。\n" << endl;
    while (WAIT_OBJECT_0 != WaitForSingleObject(h_event1, 300))
    {
        cout << "线程1正在等待event1\n" << endl;
    }
    cout << "线程1等到了event1,线程1结束。\n" << endl;
    ResetEvent(h_event1);
    return 0;
}

DWORD WINAPI FunProc2(LPVOID lpParameter)
{
    cout << "线程2开始运行。\n" << endl;
    while (WAIT_OBJECT_0 != WaitForSingleObject(h_event2, 300))
    {
        cout << "线程2正在等待event2\n" << endl;
    }
    cout << "线程2等到了event2,线程2结束。\n" << endl;
    Sleep(350);
    SetEvent(h_event1);
    return 0;
}

int main(int argc, char** argv)
{
    h_event1 = CreateEvent(NULL, true, false, _T("event_one"));
    h_event2 = CreateEvent(NULL, false, false, _T("event_two"));

    HANDLE hThread1;
    hThread1 = CreateThread(NULL, 0, FunProc1, NULL, 0, NULL);

    HANDLE hThread2;
    hThread2 = CreateThread(NULL, 0, FunProc2, NULL, 0, NULL);

    Sleep(1000);
    SetEvent(h_event2);

    while (WaitForSingleObject(hThread1, 150) != WAIT_OBJECT_0 || WaitForSingleObject(hThread2, 150) != WAIT_OBJECT_0)
    {
        cout << "线程还没有结束,主程序等了150ms。\n" << endl;
    }

    CloseHandle(hThread1);
    CloseHandle(hThread2);
    CloseHandle(h_event1);
    CloseHandle(h_event2);

    system("pause");

}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)