rest - 临时锁定资源,直到 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状态码。我想,我还不了解频道。可以尝试使用互斥锁吗?
解决方案
不是最好的解决方案,但它有效:
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)
}()
}
}
推荐阅读
- excel - vba 等待命令提示符完成?
- java - 我在 Android Studio 中编写了一个按钮来更改屏幕,但是当我尝试打开它时它一直在崩溃
- node.js - /usr/bin/fuser -k 5003/tcp 在 nodejs 中失败,但在 shell 中工作
- javascript - 从javascript中具有不同属性的2个数组中获取不同的元素
- html - 在 chrome 浏览器的网站右侧显示额外的空白,但在 Firefox 浏览器上工作正常
- clickhouse - 在 Clickhouse 中的多个列上应用 argMax
- haskell - 使用(伪)可变映射调用函数(并更改映射)
- python - Arduino WebSockets 服务器和 Python 客户端之间的冻结和连接问题
- javascript - 使用 axios 的不一致数据响应
- python - modify_header 扩展和标题未加载,浏览器正在启动:Selenium with Python