在CSDN下C一下回答的:
在Windows系统下只能运行一个实例,使用互斥量(Mutex)来实现。互斥量是一种同步原语,用于确保在同一时间内只有一个线程可以访问特定资源。
使用了 QSharedMemory 类来创建共享内存,QSystemSemaphore 类来创建系统信号量。它们可以确保只有一个实例可以成功加锁,其他实例则会被拒绝。如果共享内存或系统信号量已存在,则说明已有实例在运行,此时可以弹出错误提示。
以下是一个使用互斥量实现的示例代码:
#include "mainwindow.h"
#include <QApplication>
#include<QSharedData>
#include<QSystemSemaphore>
#include <QMessageBox>
#include <QSharedMemory>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// 设置唯一的共享内存键值
const QString sharedMemKey = "MyApplication";
// 创建共享内存和系统信号量
QSharedMemory sharedMem(sharedMemKey);
QSystemSemaphore systemSemaphore(sharedMemKey, 1);
// 尝试加锁共享内存
if (!sharedMem.create(1) && sharedMem.error() == QSharedMemory::AlreadyExists) {
// 共享内存已存在,说明已有实例在运行
QMessageBox::critical(nullptr, "Error", "Another instance of the application is already running.");
return 1;
}
// 尝试加锁系统信号量
if (!systemSemaphore.acquire()) {
// 无法加锁系统信号量,说明已有实例在运行
QMessageBox::critical(nullptr, "Error", "Another instance of the application is already running.");
return 1;
}
// 运行应用程序逻辑
MainWindow w;
w.show();
// 释放系统信号量
systemSemaphore.release();
return a.exec();
}