Home > Backend Development > Golang > How to Ensure a Single Instance of a Golang Executable Runs on Windows?

How to Ensure a Single Instance of a Golang Executable Runs on Windows?

DDD
Release: 2024-11-27 08:09:10
Original
201 people have browsed it

How to Ensure a Single Instance of a Golang Executable Runs on Windows?

Ensuring Single Instance Execution of a Golang Executable on Windows

To prevent multiple instances of an executable from running concurrently, implementing a Global Mutex mechanism is essential. Here's a solution for achieving this in Golang on a Windows machine:

Utilizing a Global Mutex:

The solution involves creating a global mutex using the CreateMutex function from the Windows kernel. A global mutex can be accessed across different user sessions, ensuring that only one instance of the executable can run at a time.

Code Example:

The following Go code demonstrates how to create a global mutex:

import (
    "syscall"
    "unsafe"
)

// CreateMutex creates a global mutex.
func CreateMutex(name string) (uintptr, error) {
    kernel32 := syscall.NewLazyDLL("kernel32.dll")
    procCreateMutex := kernel32.NewProc("CreateMutexW")

    ret, _, err := procCreateMutex.Call(
        0,
        0,
        uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(name))),
    )
    if int(err.(syscall.Errno)) == 0 {
        return ret, nil
    }

    return ret, err
}

// SampleMutexName provides an example of creating a global mutex.
func SampleMutexName() {
    _, err := CreateMutex("Global\MyMutexName")
    if err != nil {
        // Handle error
    }
}
Copy after login

Conclusion:

By creating a global mutex, you can ensure that only one instance of your Golang executable is running at any given time. This solution effectively prevents multiple instances from consuming system resources unnecessarily.

The above is the detailed content of How to Ensure a Single Instance of a Golang Executable Runs on Windows?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template