WIN32互斥体CreateMutex以及限制多开

CreateMutex(

LPSECURITY_ATTRIBUTES 【lpMutexAttributes】,    //指向安全属性的指针
BOOL 【bInitialOwner】,    //标志初始所有权
LPCTSTR 【lpName】    //指向mutex对象名称的指针
);
// Mutex0616.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <WINDOWS.H>
int main(int argc, char* argv[])
{
    //创建互斥体
    HANDLE hMutex = CreateMutex(NULL,FALSE,"xyz");
    //获取令牌
    WaitForSingleObject(hMutex,INFINITE);

    for (int i =0;i<10;i++)
    {
        Sleep(1000);
        printf("A进程的X线程:%d\n",i);
    }

    ReleaseMutex(hMutex);

    return 0;
}
// Mutex0616.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <WINDOWS.H>
int main(int argc, char* argv[])
{
    //创建互斥体
    HANDLE hMutex = CreateMutex(NULL,FALSE,"xyz");
    //获取令牌
    WaitForSingleObject(hMutex,INFINITE);
    
    for (int i =0;i<10;i++)
    {
        Sleep(1000);
        printf("B进程的Y线程:%d\n",i);
    }
    
    ReleaseMutex(hMutex);
    
    return 0;
}

 

// Mutex0616.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <WINDOWS.H>
int main(int argc, char* argv[])
{
    //创建互斥体
    HANDLE hMutex = CreateMutex(NULL,FALSE,"xyz");

    DWORD dret = GetLastError();
    if(hMutex)
    {
        if (ERROR_ALREADY_EXISTS == dret)
        {
            CloseHandle(hMutex);
            return 0;
        }
    }
    else
    {
        printf("创建失败!程序退出!");
        CloseHandle(hMutex);
        return 0;
    }
    //获取令牌
    //WaitForSingleObject(hMutex,INFINITE);
    
    for (;;)
    {
        Sleep(1000);
        printf("A进程的X线程\n");
    
    }
    //ReleaseMutex(hMutex);
    
    return 0;
}

 

.

posted @ 2020-06-16 16:58  温暖了寂寞  阅读(1187)  评论(0编辑  收藏  举报