gpt4 book ai didi

go - 选择 block 如何等待 ctx.Done() 操作?

转载 作者:行者123 更新时间:2023-12-01 22:45:54 25 4
gpt4 key购买 nike

在下面的代码中:

    ctx, cancel := context.WithTimeout(req.Context(), 5000*time.Second)

// Wait for the response or timeout
select {
case <-ctx.Done():
log.Println("timeout, cancel work...")

// Cancel the request and wait for it to complete
// this will shutdown the go-routine immediately
tr.CancelRequest(req)
log.Println(<-ch)

case err := <-ch:
// do something
}
select同时等待两个接收操作。一个接收操作( <-ch)是一个 block 操作

在执行 select 中 block ,是 ctx.Done()select 中多次调用 block ,验证,如果 ctx.Done()返回一个 channel ?直到 <-ch被封锁了……

最佳答案

Spec: Select statements:

For all the cases in the statement, the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once, in source order, upon entering the "select" statement.


select来电 ctx.Done()只有一次。它返回一个 channel ,并监视来自该 channel 的接收操作是否可以继续。

如果 5000*time.Second超时到期,或者如果父上下文( req.Context() )被取消(例如超时或它的 cancel() 函数被调用),那么由 ctx.Done() 返回的 channel 将被关闭,因此可以继续从它接收(它不再是阻塞操作)。 Spec: Receive operator:

A receive operation on a closed channel can always proceed immediately, yielding the element type's zero value after any previously sent values have been received.

关于go - 选择 block 如何等待 ctx.Done() 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62423209/

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