登录
首页 >  Golang >  Go问答

适时打印消息以避免信号量阻塞调用者

来源:stackoverflow

时间:2024-02-29 20:48:24 311浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《适时打印消息以避免信号量阻塞调用者》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我在 go 中有以下代码,使用信号量库作为示例:

package main

import (
    "fmt"
    "context"
    "time"
    "golang.org/x/sync/semaphore"
)

// this protects the lockedvar variable
var lock *semaphore.weighted
// only one go routine should be able to access this at once
var lockedvar string

func acquirelock() {
    err := lock.acquire(context.todo(), 1)
    if err != nil {
        panic(err)
    }
}

func releaselock() {
    lock.release(1)
}

func uselockedvar() {
    acquirelock()
    fmt.printf("lockedvar used: %s\n", lockedvar)
    releaselock()
}

func causedeadlock() {
    acquirelock()

    // calling this from a function that's already
    // locked the lockedvar should cause a deadlock.
    uselockedvar()

    releaselock()
}

func main() {
    lock = semaphore.newweighted(1)
    lockedvar = "this is the locked var"

    // this is only on a separate goroutine so that the standard
    // go "deadlock" message doesn't print out.
    go causedeadlock()

    // keep the primary goroutine active.
    for true {
        time.sleep(time.second)
    }
}

有没有办法让 acquirelock() 函数调用在超时后打印一条消息,表明存在潜在的死锁,但又不解除调用阻塞?我希望死锁持续存在,但在达到超时时写入日志消息。所以 tryacquire 并不完全是我想要的。

我想要的伪代码示例:

afterFiveSeconds := func() {
    fmt.Printf("there is a potential deadlock\n")
}
lock.Acquire(context.TODO(), 1, afterFiveSeconds)

如果 acquire 调用阻塞超过 5 秒,则此示例中的 afterfiveseconds 调用将调用 afterfiveseconds 回调,但不会取消对调用者的阻止。它将继续阻塞。


正确答案


我想我已经找到了解决问题的方法。

func acquireLock() {
    timeoutChan := make(chan bool)

    go func() {
        select {
        case <-time.After(time.Second * time.Duration(5)):
            fmt.Printf("potential deadlock while acquiring semaphore\n")
        case <-timeoutChan:
            break
        }
    }()

    err := lock.Acquire(context.TODO(), 1)
    close(timeoutChan)
    if err != nil {
        panic(err)
    }
}

以上就是《适时打印消息以避免信号量阻塞调用者》的详细内容,更多关于的资料请关注golang学习网公众号!

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