我有以下请求队列:
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
}
是否有可能只使用原子包,不使用互斥锁,类型仅为type AtomicRequestQueue []*http.Request
,这是否会带来任何性能优势?
使用通道,如chan *http.Request
。通道的字面意思是一个FIFO队列。
你所说的Enqueue
将只是一个发送操作c <- req
,而你所说的Dequeue
将只是一个接收操作req := <-c
。
是否可以只使用原子包
你没有说明这个线程安全队列的真正目的是什么,但是你上面给出的用例似乎需要同步,即mutual的对共享资源的封闭访问。atomic
包中的类型只保证其他线程以一致的方式观察到操作的结果。没有互斥性
如果你的队列需要比你实际显示的更多的业务逻辑,通道可能太原始了;在这种情况下,互斥锁可能是最好的选择。如果您希望有大量的读操作,可以使用sync.RWMutex
来减少锁争用。