临时锁定资源,直到 goroutine 完成

我有一个方法,它发送 HTTP 状态代码202 Accepted作为成功请求的指示符,并在其中运行另一个进程(goroutine)。像这样的东西:


return func(w http.ResponseWriter, r *http.Request) {

    w.WriteHeader(http.StatusAccepted)

    go func() {

        time.Sleep(2 * time.Second)

    }()

}

我想暂时锁定资源以防止 goroutine 进程的多次执行。


return func(w http.ResponseWriter, r *http.Request) {

    c := make(chan bool)


    select {

    case _, unlocked := <-c:

        if unlocked {

            break

        }

    default:

        w.WriteHeader(http.StatusLocked)

        return

    }


    w.WriteHeader(http.StatusAccepted)

    go func(c chan bool) {

        time.Sleep(2 * time.Second)

        c <- true

    }(c)

}

我总是得到423 Locked状态码。我想,我还不了解频道。可以尝试使用互斥锁吗?


慕姐8265434
浏览 91回答 1
1回答

汪汪一只猫

不是最好的解决方案,但它有效:func (h *HookHandler) NewEvents() http.HandlerFunc {&nbsp; &nbsp; eventsLocker := struct {&nbsp; &nbsp; &nbsp; &nbsp; v&nbsp; &nbsp;bool&nbsp; &nbsp; &nbsp; &nbsp; mux *sync.Mutex&nbsp; &nbsp; }{&nbsp; &nbsp; &nbsp; &nbsp; v:&nbsp; &nbsp;true,&nbsp; &nbsp; &nbsp; &nbsp; mux: &sync.Mutex{},&nbsp; &nbsp; }&nbsp; &nbsp; return func(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; &nbsp; &nbsp; if !eventsLocker.v {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; w.WriteHeader(http.StatusLocked)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; w.WriteHeader(http.StatusAccepted)&nbsp; &nbsp; &nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; defer eventsLocker.mux.Unlock()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; defer func() { eventsLocker.v = true }()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; eventsLocker.mux.Lock()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; eventsLocker.v = false&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(2 * time.Second)&nbsp; &nbsp; &nbsp; &nbsp; }()&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go