1、 C++11 thread类多线程编程

#include "stdafx.h"
#include <iostream>
#include <thread>
#include <Windows.h>
#include <mutex>

using namespace std;


mutex mu;  //线程互斥对象

int totalNum = 100;

void thread01()
{
    while (totalNum > 0)
    {
        mu.lock(); //同步数据锁
        cout << totalNum << endl;
        totalNum--;
        Sleep(100);
        mu.unlock();  //解除锁定
    }
}
void thread02()
{
    while (totalNum > 0)
    {
        mu.lock();
        cout << totalNum << endl;
        totalNum--;
        Sleep(100);
        mu.unlock();
    }
}

//两个线程买票,到哪个线程,锁住,totalNum票总数减1,解锁

int _tmain(int argc, _TCHAR* argv[])
{
    thread task01(thread01);
    thread task02(thread02);
    task01.detach();
    task02.detach();
    system("pause");
    return 0;
}

 2、C++使用Windows API CreateMutex函数多线程编程

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

using namespace std;

HANDLE hMutex = NULL; //互斥量
int totalNum = 100;

DWORD WINAPI thread01(LPVOID lvParamter)
{
//    for (int i = 0; i < 10; i++)
//    {
    while (TRUE)
    {
        WaitForSingleObject(hMutex, INFINITE); //互斥锁
        if (totalNum > 0)
        {
            totalNum--;
            cout << "Thread 01 is working! == "<<totalNum << endl;
        }
        ReleaseMutex(hMutex); //释放互斥锁
        Sleep(10);
    }
        
//    }
    return 0;
}

DWORD WINAPI thread02(LPVOID lvParamter)
{
//    for (int i = 0; i < 10; i++)
//    {
    while (TRUE)
    {
        WaitForSingleObject(hMutex, INFINITE); //互斥锁
        if (totalNum > 0)
        {
            totalNum--;
            cout << "Thread 02 is working! == "<<totalNum << endl;
        }

        ReleaseMutex(hMutex); //释放互斥锁
        Sleep(10);
    }
        
//    }
    return 0;
}

//两个线程买票,到哪个线程,锁住,totalNum票总数减1,解锁

int _tmain(int argc, _TCHAR* argv[])
{
    hMutex = CreateMutex(NULL, FALSE, (LPCWSTR)"Test"); //创建互斥量
    HANDLE hThread = CreateThread(NULL, 0, thread01, NULL, 0, NULL);  //创建线程01
    hThread = CreateThread(NULL, 0, thread02, NULL, 0, NULL);     //创建线程01
    CloseHandle(hThread); //关闭句柄
    system("pause");
    return 0;
}