Home > Article > Backend Development > How Can I Ensure Only One Instance of a Go Executable Runs on Windows?
Ensuring only a single instance of an executable runs at a time is crucial for preventing multiple instances of the same program from consuming system resources or creating conflicts. This article explores how to achieve single-instance execution in Golang for Windows systems using a Global Mutex.
A global mutex is a synchronization primitive that allows multiple processes or threads to share access to a shared resource by preventing concurrent access. In this case, using a global mutex named "SomeMutexName" across all user sessions ensures that only a single instance of the executable can run.
import ( "syscall" "unsafe" ) 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 } } func main() { _, err := CreateMutex("Global\SomeMutexName") if err != nil { return } }
This code initializes the Windows API function "CreateMutexW" from the "kernel32.dll" library using the syscall package. It then calls this function with the global mutex name to create a named mutex. If the function returns without an error, it indicates that there is no other instance of the executable running. Otherwise, it means that another instance is already running.
While the code provided addresses this specific issue for Windows machines, it's worth noting that the Global Mutex technique is not portable across all platforms. Each platform has its own mechanisms for implementing instance locking. For example, on Unix-like systems, a "lockfile" approach or the "fcntl" function with "F_SETLK" can be employed to achieve similar functionality.
The above is the detailed content of How Can I Ensure Only One Instance of a Go Executable Runs on Windows?. For more information, please follow other related articles on the PHP Chinese website!