C++ implementation of the method to ensure that the application has only one running instance under Windows

The code of the first program

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

using namespace std;

//线程1
DWORD WINAPI Fun1Proc(LPVOID lpParameter);

//线程2
DWORD WINAPI Fun2Proc(LPVOID lpParameter);

int tickets = 100;
HANDLE hMutex;

int main()
{
    
    
	HANDLE hThread1;
	HANDLE hThread2;

	//创建互斥对象
	//第一个参数:是一个结构体指针,NULL表示让互斥对象使用默认的安全性
	//第二个参数:指定互斥对象的初始拥有者,FALSE表示main函数不获得所有权
	//第三个参数:指定互斥对象的名称,NULL表示创建一个匿名的互斥对象
	hMutex = CreateMutex(NULL, FALSE, L"tickets");

	//创建线程
	hThread1 = CreateThread(NULL, 0, Fun1Proc, NULL, 0, NULL);
	hThread2 = CreateThread(NULL, 0, Fun2Proc, NULL, 0, NULL);
	CloseHandle(hThread1);
	CloseHandle(hThread2);
	Sleep(4000);


	return 0;

}

//线程1入口
DWORD WINAPI Fun1Proc(LPVOID lpParameter)
{
    
    
	char buf[100] = {
    
     0 };
	while (TRUE)
	{
    
    
		//上锁,设置无信号
		//第一个参数:传递已创建的互斥对象的句柄hMutex
		//第二个参数:INFINITE表示一直等待,直到有信号才返回
		WaitForSingleObject(hMutex, INFINITE);
		if (tickets > 0)
		{
    
    
			sprintf_s(buf, "thread1 sell ticket : %d\n", tickets);
			cout << buf;
			tickets--;
		}
		else
			break;
		ReleaseMutex(hMutex);  //解锁
	}
	return 0;
}

//线程2入口
DWORD WINAPI Fun2Proc(LPVOID lpParameter)
{
    
    
	char buf[100] = {
    
     0 };
	while (TRUE)
	{
    
    
		WaitForSingleObject(hMutex, INFINITE);
		if (tickets > 0)
		{
    
    
			sprintf_s(buf, "thread2 sell ticket : %d\n", tickets);
			cout << buf;
			tickets--;
		}
		else
			break;
		ReleaseMutex(hMutex);  //解锁
	}
	return 0;
}

The code of the second program adds 30 to 38 lines more on the basis of the first

Insert picture description here

Then run the first program, and then run the second program, the result is as follows

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_50188452/article/details/114825039