golang reset locked mutex code example

Example: golang reset locked mutex

package main

import (
    "errors"
    "fmt"
    "sync"
    "time"

    "golang.org/x/sync/semaphore"
)

var sem = semaphore.NewWeighted(1)

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            if err := onlyOne(); err != nil {
                fmt.Println(err)
            }
        }()
        time.Sleep(time.Second)
    }
    wg.Wait()
}

func onlyOne() error {
    if !sem.TryAcquire(1) {
        return errors.New("busy")
    }
    defer sem.Release(1)
    fmt.Println("working")
    time.Sleep(5 * time.Second)
    return nil
}