【发布时间】:2021-09-13 18:35:59
【问题描述】:
以下是我遇到的场景的简化示例。去游乐场here.
主要方法是定期调用process函数。进程函数获取一个锁,它必须在返回之前或在应用程序因中断而关闭之前释放。
通过取消传递给process 的上下文来处理中断。在我的示例中,我只是取消了上下文。
如何确保在取消上下文时解锁逻辑执行完成?
ATM,在我的测试中,逻辑没有被执行完成。例程已启动,但在程序退出之前似乎并未完成。
好像主方法正在退出,中途杀死例程。那可能吗?如何确保例程始终在程序退出之前完成?谢谢!
package main
import (
"fmt"
"context"
"time"
"sync"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Add(1)
go func(){
fmt.Println("Started periodic process")
defer wg.Done()
ticker := time.NewTicker(20 * time.Millisecond)
for {
select {
case <-ticker.C:
process(ctx)
case <-ctx.Done():
ticker.Stop()
}
}
fmt.Println("Finished periodic process")
}()
time.Sleep(100 * time.Millisecond)
// cancel context
cancel()
wg.Wait()
}
func process(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
<-ctx.Done()
// unlock resources
fmt.Println("Unlocking resources")
time.Sleep(20 * time.Millisecond)
fmt.Println("Unlocked resources")
}()
// do some work
fmt.Println("Started process")
// acquire lock, in actual process
// acquiring lock will fail unless
// it was released be previous process
// run
fmt.Println("Acquired lock")
time.Sleep(10 * time.Millisecond)
fmt.Println("Finished process")
}
【问题讨论】:
-
用global waitgroup 更新了您的游乐场。这有帮助吗?
标签: go