C++之多线程入门

1、最简单的多线程任务及利用Mutex实现线程互斥,运行效果如下:
C++之多线程入门_第1张图片
2、代码如下:

// MultiThread.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include 
#include 

DWORD WINAPI Fun1Proc(LPVOID lpParameter);
DWORD WINAPI Fun2Proc(LPVOID lpParameter);
unsigned int nTickets = 50;
HANDLE hMutex; // 线程互斥

int main()
{
    HANDLE hThreadl;
    HANDLE hThread2;

    hMutex = CreateMutex(NULL, FALSE, NULL);

    hThreadl = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
    hThread2 = CreateThread(NULL, 0, Fun2Proc, NULL, 0, NULL);
    CloseHandle(hThreadl);
    CloseHandle(hThread2);

    Sleep(500); //延迟主线程结束时间,等待子线程执行完成100次

    printf("Tickets are sold out:%d!", nTickets);

    return 0;
}

DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
    while (TRUE)
    {
        WaitForSingleObject(hMutex, INFINITE);

        if (nTickets < 1)
        {
            break;
        }
        printf("LM sells ticket:%d! \n", nTickets--);

        ReleaseMutex(hMutex);
    }
   
    return 0;
}

DWORD WINAPI Fun2Proc(LPVOID lpParameter)
{
    while (TRUE)
    {
        WaitForSingleObject(hMutex, INFINITE);

        if (nTickets < 1)
        {
            break;
            
        }

        printf("JK sells ticket:%d! \n", nTickets--);

        ReleaseMutex(hMutex);
    }

    return 0;
}

你可能感兴趣的:(C++应用,多线程,线程互斥)