Windows API CreateMutex和C++11 thread类多线程编程比较

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

 

转载于:https://www.cnblogs.com/dianrain/p/9279584.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值