Home > Backend Development > Golang > How to Ensure Only One Instance of a Go Application Runs System-Wide Using a Global Mutex?

How to Ensure Only One Instance of a Go Application Runs System-Wide Using a Global Mutex?

Linda Hamilton
Release: 2024-11-30 05:32:25
Original
585 people have browsed it

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")
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template