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;
}

猜你喜欢

转载自www.cnblogs.com/dianrain/p/9279584.html