【发布时间】:2021-11-18 22:30:52
【问题描述】:
我有以下请求队列:
type RequestQueue struct {
Requests []*http.Request
Mutex *sync.Mutex
}
func (rq *RequestQueue) Enqueue(req *http.Request) {
rq.Mutex.Lock()
defer rq.Mutex.Unlock()
rq.Requests = append(rq.Requests, req)
}
func (rq *queue) Dequeue() (*http.Request, error) {
rq.Mutex.Lock()
defer rq.Mutex.Unlock()
if len(rq.Requests) == 0 {
return nil, errors.New("dequeue: queue is empty")
}
req := rq.Requests[0]
rq.Requests = rq.Requests[1:]
return req, nil
}
是否可以只使用 atomic 包而不使用 Mutex,类型只是 type AtomicRequestQueue []*http.Request,这会带来任何性能优势吗?
【问题讨论】:
-
不,您需要在此处进行互斥锁提供的同步。为什么不使用已经在运行时高度优化的简单缓冲通道?
-
@JimB 因为 afaik tt 无法动态调整大小。
-
这很少是一个真正的问题,因为无论如何都应该以某种方式限制最大大小,并且通道具有在缓冲区满时能够自动阻塞的好处。
-
可以动态调整大小...
标签: go concurrency queue thread-safety