登录
首页 >  Golang >  Go问答

Postgres 锁在多个 goroutine 中表现不稳定

来源:stackoverflow

时间:2024-03-01 16:00:26 209浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《Postgres 锁在多个 goroutine 中表现不稳定》,聊聊,我们一起来看看吧!

问题内容

我在 go 例程和 postgresql 9.5 上遇到了 pg_locks 的一些不一致行为。

当我创建额外的 goroutines 并调用 select pg_try_advisory_lock(1); 时,结果不一致。

我可以在某个时刻尝试获取锁,失败,再试一次并设法获取它,同时没有任何人显式释放锁。

我创建了一个小程序来重现该问题。

程序流程

  1. 创建 10 个 goroutine。他们每个人都试图在初始化时获得相同的锁。
  2. 每一秒,每个实例都会尝试再次获取锁(如果尚未获取锁)。
  3. 我每秒都会探测所有实例并计算有多少实例已获得锁定。

预期行为:

在任何给定时刻只有 1 个 goroutine 拥有锁。

实际结果:

设法获取锁的 goroutine 数量随着时间的推移而增加。

package main

var dbmap *gorp.dbmap // init code omitted for brevity

func main() {
    setup(10)
    fmt.println("after initialization,", countowners(), "instances of lockowners have the lock!")

    for {
        if _, err := dbmap.exec("select pg_sleep(1)"); err != nil {
            panic(err)
        }

        fmt.println(countowners(), "instances of lockowners have the lock!")
    }
}

func countowners() int {
    possesslock := 0
    for _, lo := range los {
        if lo.haslock {
            possesslock++
        }
    }
    return possesslock
}

var los []*lockowner

func setup(instancecount int) {
    var wg sync.waitgroup
    for i := 0; i < instancecount; i++ {
        wg.add(1)
        newinstance := lockowner{}
        los = append(los, &newinstance)
        go newinstance.begin(time.second, &wg, i+1)
    }
    wg.wait()
}

type lockowner struct {
    id      int
    ticker  *time.ticker
    haslock bool
}

func (lo *lockowner) begin(interval time.duration, wg *sync.waitgroup, id int) {
    lo.ticker = time.newticker(interval)
    lo.id = id
    go func() {
        lo.trytogetlock()
        wg.done()
        for range lo.ticker.c {
            lo.trytogetlock()
        }
    }()
}

func (lo *lockowner) trytogetlock() {

    if lo.haslock {
        return
    }

    locked, err := dbmap.selectstr("select pg_try_advisory_lock(4);")
    if err != nil {
        panic(err)
    }

    if locked == "true" {
        fmt.println(lo.id, "did get lock!")
        lo.haslock = true
    }
}

该程序的输出各不相同,但通常是这样的:

1 Did get lock!
after initialization, 1 instances of lockOwners have the lock!
1 instances of lockOwners have the lock!
2 Did get lock!
2 instances of lockOwners have the lock!
2 instances of lockOwners have the lock!
7 Did get lock!
3 instances of lockOwners have the lock!
3 instances of lockOwners have the lock!
6 Did get lock!
4 instances of lockOwners have the lock!

我的问题:

  1. 以这种方式使用 pg_locks 时,我应该期望得到什么保护?
  2. 某些 goroutine 无法获取锁的原因是什么?
  3. 同一个 goroutine 在下一次尝试中成功执行此操作的原因是什么?

    • 是否该线程是被锁定的资源,并且每次 goroutine 触发时都会从不同的线程执行此操作?这可以解释不一致的行为。

解决方案


经过几个月通过 gorp 使用 PostgreSQL 的经验,我想我理解了这种行为:

  • gorp 维护一个连接池。
  • 每当我们创建一笔交易时,都会随机选择这些连接之一(?)。
  • dbMap.SomeCommand() 创建事务、执行某些命令并提交事务。
  • pg_try_advisory_lock 适用于 session level
  • A session is synonymous with a TCP connection,因此绝不是稳定或永久的。
  • 池中的连接会尽可能保持使用相同的会话,但会在需要时重置它。

每当我们执行 dbMap.SelectStr("SELECT pg_try_advisory_lock(4);") 时,就会从池中选择一个连接。然后创建一个事务,它获取会话级别的锁,然后提交。

当另一个 go-routine 尝试执行相同操作时,它有可能会使用相同会话,这可能取决于从池中获取的连接。由于锁定是在会话级别完成的 - 新事务能够再次获取锁定。

理论要掌握,实操不能落!以上关于《Postgres 锁在多个 goroutine 中表现不稳定》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>