donglu9898 2017-03-13 00:16
浏览 142
已采纳

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

Redigo is a golang client for the redis database. It uses struct Pool to maintain a pool of connections. This struct holds a mutex lock for application putting and getting connection parallelly.

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

In its get method, connection pool removes stale (idle timeout) connections firstly. When finding a stale connection, the pool pops it, releases lock, then closes connection, tries to acquire lock again.

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()
        }
    }

Why does pool unlock and try to acquire lock again, instead of just unlocking before function returns? I guess closing a connection may cost quite a lot time, which will slow down other goroutine waiting on this mutex.

Here is the whole Pool get method

  • 写回答

1条回答 默认 最新

  • donglun7151 2017-03-13 02:22
    关注

    Close a connection may cost quite a lot time, which will slow down other goroutine waiting on this mutex. As what @Cerise Limón said - It seems unwise to lock all use of the pool for this time.

    After unlocking the mutex, one of the waiting goroutines gets the mutex. Although goroutine for get method still needs to remove stale connections, the one for put method can put connection to pool and continue to do other work as soon as possible.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退