亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

臨時鎖定資源,直到 goroutine 完成

臨時鎖定資源,直到 goroutine 完成

Go
慕姐8265434 2022-07-11 15:00:05
我有一個方法,它發送 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狀態碼。我想,我還不了解頻道??梢試L試使用互斥鎖嗎?
查看完整描述

1 回答

?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

不是最好的解決方案,但它有效:


func (h *HookHandler) NewEvents() http.HandlerFunc {

    eventsLocker := struct {

        v   bool

        mux *sync.Mutex

    }{

        v:   true,

        mux: &sync.Mutex{},

    }


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

        if !eventsLocker.v {

            w.WriteHeader(http.StatusLocked)

            return

        }


        w.WriteHeader(http.StatusAccepted)


        go func() {

            defer eventsLocker.mux.Unlock()

            defer func() { eventsLocker.v = true }()


            eventsLocker.mux.Lock()

            eventsLocker.v = false


            time.Sleep(2 * time.Second)

        }()

    }

}


查看完整回答
反對 回復 2022-07-11
  • 1 回答
  • 0 關注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號