gpt4 book ai didi

go - 如何终止从 goroutine 调用的函数

转载 作者:行者123 更新时间:2023-12-01 22:44:21 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





cancel a blocking operation in Go

(2 个回答)



How to cancel goroutines after certain amount of time

(1 个回答)



Goroutine Timeout

(2 个回答)



Cancel go func()

(2 个回答)



Cancelling user specific goroutines [closed]

(2 个回答)


1年前关闭。



    package main

import (
"context"
"errors"
"fmt"
"time"
)

type result struct {
record interface{}
err error
}

func longRun() {
for i := 0; ; i++ {
time.Sleep(1 * time.Second)
fmt.Println("This is very long running ", i)
}
}

func process() (interface{}, error) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

quit := make(chan int)

go func() {
for {
select {
case <-quit:
fmt.Println("quit")
return
default:
longRun()
return
}
}
}()

select {
case <-ctx.Done():
close(quit)
return nil, errors.New("Execution canceled")
}
}

func main() {
value, err := process()
fmt.Println("value", value)
fmt.Println("err", err)

//prevent main function termination
for i := 0; ; i++ {
}
}

超时时,process() 函数中的 goroutine 终止,但我如何终止函数 longrun()。

样本输出
This is very long running  0
This is very long running 1
value <nil>
err Execution canceled
This is very long running 2
This is very long running 3
This is very long running 4

正如输出所示,即使进程函数返回,longrun() 函数仍在执行。

如何在返回 process() 函数后立即终止 longrun() 执行

最佳答案

没有办法立即终止一个 goroutine。您可以使用上下文向 goroutine 发送取消通知,但 goroutine 必须定期检查上下文并在上下文被取消时终止。在使用另一个 channel 从函数返回之前,您可以等待长时间运行的 goroutine 终止:

func longRunning(ctx context.Context,done chan struct{}) {
defer close(done)
for {
...
select {
case <-ctx.Done():
return
default:
}
}
}

...
ctx, cancel:=context.WithCancel(context.Background())
defer cancel()
ch:=make(chan struct{})
go longRunning(ctx,ch)
// Do things
cancel() // Stop goroutine
// wait for the long running to terminate
<-ch

关于go - 如何终止从 goroutine 调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61897551/

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