GOLANG使用Context管理关联goroutine
来源:互联网 发布:scala编程完整版 pdf 编辑:程序博客网 时间:2024/06/08 05:35
原文:https://gocn.io/article/333
一般一个业务很少不用到goroutine的,因为很多方法是需要等待的,例如http.Server.ListenAndServe
这个就是等待的,除非关闭了Server或Listener,否则是不会返回的。除非是一个API服务器,否则肯定需要另外起goroutine发起其他的服务,而且对于API服务器来说,在http.Handler
的处理函数中一般也需要起goroutine,如何管理这些goroutine,在GOLANG1.7提供context.Context
。
先看一个简单的,如果启动两个goroutine,一个是HTTP,还有个信号处理的收到退出信号做清理:
wg := sync.WaitGroup{}defer wg.Wait()wg.Add(1)go func() { defer wg.Done() ss := make(os.Signal, 0) signal.Notify(ss, syscall.SIGINT, syscall.SIGTERM) for s := ss { fmt.Println("Got signal", s) break }}()wg.Add(1)go func() { defer wg.Done() svr := &http.Server{ Addr:":8080", Handler:nil, } fmt.Println(svr.ListenAndServe())}
很清楚,起了两个goroutine,然后用WaitGroup等待它们退出。如果它们之间没有交互,不互相影响,那真的是蛮简单的,可惜这样是不行的,因为信号的goroutine收到退出信号后,应该通知server退出。暴力一点的是直接调用svr.Close()
,但是如果有些请求还需要取消怎么办呢?最好用Context了:
wg := sync.WaitGroup{}defer wg.Wait()ctx,cancel := context.WithCancel(context.Background())wg.Add(1)go func() { defer wg.Done() ss := make(os.Signal, 0) signal.Notify(ss, syscall.SIGINT, syscall.SIGTERM) for { select { case <- ctx.Done(): return case s := <- ss: fmt.Println("Got signal", s) cancel() // 取消请求,通知用到ctx的所有goroutine return } }}()wg.Add(1)go func() { defer wg.Done() defer cancel() svr := &http.Server{ Addr:":8080", Handler:nil, } go func(){ select { case <- ctx.Done(): svr.Close() } } fmt.Println(svr.ListenAndServe())}
这个方式可以在新开goroutine时继续使用,譬如新加一个goroutine,里面读写了UDPConn:
wg.Add(1)go func() { defer wg.Done() defer cancel() var conn *net.UDPConn if conn,err = net.Dial("udp", "127.0.0.1:1935"); err != nil { fmt.Println("Dial UDP server failed, err is", err) return } fmt.Println(UDPRead(ctx, conn))}()UDPRead = func(ctx context.Context, conn *net.UDPConn) (err error) { wg := sync.WaitGroup{} defer wg.Wait() ctx, cancel := context.WithCancel(ctx) wg.Add(1) go func() { defer wg.Done() defer cancel() for { b := make([]byte, core.MTUSize) size, _, err := conn.ReadFromUDP(b) // 处理UDP包 b[:size] } }() select { case <-ctx.Done(): conn.Close() } return}
如果只是用到HTTP Server,可以这么写:
func run(ctx contex.Context) { server := &http.Server{Addr: addr, Handler: nil} go func() { select { case <-ctx.Done(): server.Close() } }() http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) { }) fmt.Println(server.ListenAndServe())}
如果需要提供一个API来让服务器退出,可以这么写:
func run(ctx contex.Context) { server := &http.Server{Addr: addr, Handler: nil} ctx, cancel := context.WithCancel(ctx) http.HandleFunc("/quit", func(w http.ResponseWriter, r *http.Request) { cancel() // 使用局部的ctx和cancel }) go func() { select { case <-ctx.Done(): server.Close() } }() fmt.Println(server.ListenAndServe())}
使用局部的ctx和cancel,可以避免cancel传入的ctx,只是影响当前的ctx。
阅读全文
0 0
- GOLANG使用Context管理关联goroutine
- 使用Golang的Context管理上下文
- golang-context(上下文管理)
- golang使用pprof检查goroutine泄露
- golang使用之使用channel限制goroutine的数量
- Golang goroutine and channel
- GoLang学习 -- goroutine使用指南
- 【GOLANG】goroutine原理
- golang-并发编程goroutine
- Golang之chan/goroutine
- Golang获取goroutine ID
- golang技术,理解goroutine
- Golang -- goroutine (一)
- golang goroutine顺序输出
- golang Context包的使用
- 跟着猫哥学Golang 15 - goroutine
- golang工作者goroutine池模型
- golang的goroutine调度机制
- byx
- php将当前时间戳增加一年(year)
- 学习总结
- java网络通信编程
- <框架篇(4)>Spring配置AOP的方式
- GOLANG使用Context管理关联goroutine
- RT-Thread的CPU使用率计算
- Canopy聚类算法
- hibernate 懒加载异常分析: failed to lazily initialize a collection of role
- 物体缓慢转向目标点
- 解决Things are going to break, please only change locale by creating wxLocale objects...
- AngularJS 教程(一)
- 机器学习知识点(三十二)微积分基础
- 下拉列表的赋值,和默认选中