#include "stdafx.h" #include "windows.h" #include <iostream> using namespace std; class MaxClientLimitInstance { public: static bool Lock(int MaxInstanceCount) { int ret = 0; for(int i = 0; i < MaxInstanceCount; ++i) { HANDLE h = ::CreateMutex(0, 1, L"test program"); if (GetLastError() == 0) { m_Handle = h; break; } else { CloseHandle(h); ret++; } } return ret < MaxInstanceCount; } static void UnLock() { if (m_Handle != NULL) { ReleaseMutex(m_Handle); CloseHandle(m_Handle); } } static HANDLE m_Handle; }; HANDLE MaxClientLimitInstance::m_Handle = 0; int _tmain(int argc, _TCHAR* argv[]) { int MaxNumber = 1; if (!MaxClientLimitInstance::Lock(MaxNumber)) { cout << "You have already run a program! This program will be closed." << endl; system("pause"); return 0; } else { cout << "Run program success! " << endl; } system("pause"); //< 等待用户输入,在游戏程序中可以对应理解为在游戏主循环中执行逻辑 MaxClientLimitInstance::UnLock(); //< 注意,要在“等待用户输入"之后ReleaseMutex,否则互斥量被释放,无法达到预期 return 0; }
原文地址:http://blog.csdn.net/coffeecato/article/details/41056491