多线程互斥锁

例子

from:https://www.cnblogs.com/ssss429170331/p/5514697.html

#include<Windows.h>
#include<iostream>
using namespace std;
//互斥锁
HANDLE hMutex1;
int flag;

DWORD WINAPI MyThread2(LPVOID lpParamter)
{
    while (1)
    {
    //没上锁的话就自己锁上,否则等着
        WaitForSingleObject(hMutex1,INFINITE);
        flag=!flag;
        cout << "MyThread1 Runing :"<<"线程2"<<" "<<flag<< endl;
        Sleep(1000);
     //解锁
        ReleaseMutex(hMutex1);
    }
}
DWORD WINAPI MyThread1(LPVOID lpParamter)
{
    while (1)
    {
        WaitForSingleObject(hMutex1,INFINITE);
        flag=!flag;
        cout << "MyThread2 Runing"<<"线程1" <<" "<<flag<< endl;
        Sleep(10);
        ReleaseMutex(hMutex1);

    }
}

int main()
{
    //创建一个锁
    hMutex1  =CreateMutex(NULL,FALSE,NULL);
    HANDLE hThread1 = CreateThread(NULL, 0, MyThread1, NULL, 0, NULL);
    CloseHandle(hThread1);

    HANDLE hThread2 = CreateThread(NULL, 0, MyThread2, NULL, 0, NULL);
    CloseHandle(hThread2);
    while(1);
    return 0;
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41127779/article/details/82701631