如果golang阻塞函数的调用程序执行了该操作,该函数会发生什么情况?
我想知道如果可中断的_调用是不可中断的,并且在上下文完成后返回,会发生什么情况。调用堆栈可能已被销毁。返回操作将执行什么操作?当一个案例返回而另一个案例仍在运行时,如果golang阻塞函数的调用程序执行了该操作,该函数会发生什么情况?,go,Go,我想知道如果可中断的_调用是不可中断的,并且在上下文完成后返回,会发生什么情况。调用堆栈可能已被销毁。返回操作将执行什么操作?当一个案例返回而另一个案例仍在运行时,select将如何执行。这个case函数调用会被终止吗?以什么方式 package main import ( "context" "fmt" "time" ) func interruptable_call() <-chan time.Time { return time.After(1 *
select
将如何执行。这个case函数调用会被终止吗?以什么方式
package main
import (
"context"
"fmt"
"time"
)
func interruptable_call() <-chan time.Time {
return time.After(1 * time.Second)
}
func A(ctx context.Context) int {
for {
select {
case <-ctx.Done():
fmt.Println("func done")
return 1
case <-interruptable_call():
fmt.Println("blocking")
}
}
return 0
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
fmt.Println("go A")
go A(ctx)
fmt.Println("go A done")
select {
case <-ctx.Done():
fmt.Println("main done")
break
}
}
主程序包
进口(
“上下文”
“fmt”
“时间”
)
func interruptable_call()我不知道你所说的“同步问题”是什么意思,因为这里没有同步。。如果要确保生成的goroutine执行了任务,则需要使用频道、等待组或任何其他方式同步goroutine
goroutine中发生了什么并不重要——如果它不与主goroutine同步,那么在主出口后它将不再存在
在goroutine中异步调用的函数的返回值无论如何对您都不可用
您可以查看阻止呼叫是如何为自己工作的:
package main
import (
"context"
"fmt"
"time"
)
func interruptable_call(sleep time.Duration) <-chan time.Time {
fmt.Println("sleeping for ", sleep*time.Second)
time.Sleep(sleep * time.Second)
return time.After(0 * time.Second)
}
func A(ctx context.Context) int {
for {
select {
case <-ctx.Done():
fmt.Println("func done")
return 1
case <-interruptable_call(2):
fmt.Println("blocking")
case <-interruptable_call(3):
fmt.Println("blocking")
case <-interruptable_call(4):
fmt.Println("blocking")
case <-interruptable_call(5):
fmt.Println("blocking")
}
}
return 0
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
fmt.Println("go A")
go A(ctx)
fmt.Println("go A done")
select {
case <-ctx.Done():
fmt.Println("main done")
break
}
}
主程序包
进口(
“上下文”
“fmt”
“时间”
)
func interruptable_call(sleep time.Duration)当一个案例返回而另一个案例仍在运行时,如何选择执行。这个case函数调用会被终止吗?以何种方式?Select按顺序运行案例,使“就绪”通道等待消息,但如果已返回的通道获得消息,Select语句将选择此案例并运行它。我不确定这在内部是如何工作的,但我的猜测是,任何已经运行的案例都已完成,任何其他案例都不会运行,因为select语句已经完成。