Home  >  Article  >  Backend Development  >  How Can I Ensure Only One Instance of a Go Executable Runs on Windows?

How Can I Ensure Only One Instance of a Go Executable Runs on Windows?

Barbara Streisand
Barbara StreisandOriginal
2024-11-27 09:24:15391browse

How Can I Ensure Only One Instance of a Go Executable Runs on Windows?

Restricting to Single Instance of Executable in Go for 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.

Global Mutex for Single-Instance Control

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.

Code Implementation

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
    }
}

Architecture of the Solution

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.

Portability to Other Platforms

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn