多線程demo

#include <iostream>
#include <Windows.h>

using namespace std;

HANDLE hMutex; // 創建互斥句柄

DWORD WINAPI Fun(LPVOID lpParamter)
{
    while (1)
    {
        WaitForSingleObject(hMutex, INFINITE); // 申請獨佔資源
        cout << "Fun dispaly!" << endl;
        Sleep(1000);
        ReleaseMutex(hMutex); // 釋放獨佔資源
    }
}

int main()
{
    HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);

    hMutex = CreateMutex(NULL, FALSE, "screen"); // 創建獨佔資源,這裏爲顯示器,字符集改爲多字節字符集

    CloseHandle(hThread); // 關閉線程句柄對象,不再使用該句柄,並沒有關閉線程,如果其它地方還要用到就不要close

    while (1)
    {
        WaitForSingleObject(hMutex, INFINITE); // 申請獨佔資源

        cout << "main display" << endl;
        Sleep(2000);
        ReleaseMutex(hMutex); // 釋放獨佔資源
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章