gpt4 book ai didi

go - redigo 连接池 - 为什么在删除陈旧连接时释放锁

转载 作者:可可西里 更新时间:2023-11-01 11:28:42 28 4
gpt4 key购买 nike

Redigo 是 redis 数据库的 golang 客户端。它使用 struct Pool 来维护连接池。该结构持有一个互斥锁,用于并行放置和获取连接的应用程序。

type Pool struct {
// ...
IdleTimeout time.Duration
mu sync.Mutex
// Stack of idleConn with most recently used at the front.
idle list.List
}

在其get 方法中,连接池首先移除过时(空闲超时)连接。当找到失效连接时,池将其弹出,释放锁,然后关闭连接,尝试再次获取锁。

func (p *Pool) get() (Conn, error) {
p.mu.Lock()

// Prune stale connections.

if timeout := p.IdleTimeout; timeout > 0 {
for i, n := 0, p.idle.Len(); i < n; i++ {
e := p.idle.Back()
if e == nil {
break
}
ic := e.Value.(idleConn)
if ic.t.Add(timeout).After(nowFunc()) {
break
}
p.idle.Remove(e)
p.release()
// Why does pool unlock and try to acquire lock again?
p.mu.Unlock()
// Close this stale connection.
ic.c.Close()
p.mu.Lock()
}
}

为什么池解锁并尝试再次获取锁,而不是在函数返回之前解锁?我想关闭一个连接可能会花费很多时间,这会减慢等待这个互斥锁的其他 goroutine 的速度。

这是全部 Pool get method

最佳答案

关闭连接可能会花费很多时间,这会减慢等待此互斥量的其他 goroutine。正如@Cerise Limón 所说 - 这次锁定所有池的使用似乎是不明智的。

解锁互斥锁后,其中一个等待的 goroutine 获得互斥锁。虽然 get 方法的 goroutine 仍然需要移除过时的连接,但是 put 方法的 goroutine 可以尽快将连接放入池中并继续做其他工作。

关于go - redigo 连接池 - 为什么在删除陈旧连接时释放锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42754823/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com