Home >Backend Development >Golang >How to Ensure Only One Instance of a Go Application Runs System-Wide Using a Global Mutex?
Restricting to Single Instance of Golang Executable with Global Mutex
It's a common requirement to enforce a single instance of an application. Golang provides a convenient solution using the sync.Mutex package. However, this method only works within a single process. To restrict the application to a single instance across the system, leveraging a global mutex is necessary.
On Windows, the kernel32.dll library offers the CreateMutexW function to create a system-wide mutex. This function requires a unique name for the mutex to identify it across processes.
Example:
var ( kernel32 = syscall.NewLazyDLL("kernel32.dll") procCreateMutex = kernel32.NewProc("CreateMutexW") ) func CreateMutex(name string) (uintptr, error) { ret, _, err := procCreateMutex.Call( 0, 0, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(name))), ) switch int(err.(syscall.Errno)) { case 0: return ret, nil default: return ret, err } } // mutexName starting with "Global\" will work across all user sessions _, err := CreateMutex("SomeMutexName")
By specifying a name starting with "Global" in CreateMutex, the mutex can be accessed across multiple user sessions. This ensures that only a single instance of the application is running on the system.
The above is the detailed content of How to Ensure Only One Instance of a Go Application Runs System-Wide Using a Global Mutex?. For more information, please follow other related articles on the PHP Chinese website!