• Golang控制子gorutine退出,并阻塞等待所有子gorutine全部退出


    Golang控制子gorutine退出,并阻塞等待所有子gorutine全部退出

    需求

    程序有时需要自动重启或者重新初始化一些功能,就需要退出之前的所有子gorutine,并且要等待所有子gorutine全部退出,以下demo可以提供思路

    实现demo

    package main
    
    import (
    	"fmt"
    	"sync"
    	"time"
    )
    
    func main() {
    	channal1 := make(chan bool,3)
    
    	wg := new(sync.WaitGroup)
    	wg.Add(3)
    	go g1(channal1,wg)
    	go g2(channal1,wg)
    	go g3(channal1,wg)
    
    	time.Sleep(time.Second * 10)
    	channal1 <- true
    	channal1 <- true
    	channal1 <- true
    	wg.Wait()
    	fmt.Println("++++>>>>all gorutine finish...<<<<++++")
    	close(channal1)
    }
    
    func g1(c chan bool,wg *sync.WaitGroup) {
    	i := 0
    	for{
    		select {
    		case <- c:
    			fmt.Printf("@@@---->>>>>g1  end<<<<<----+++
    ")
    			wg.Done()
    			return
    		default:
    			i++
    			fmt.Printf("+++>>>>>g1  working---%d---<<<<<+++
    ",i)
    		}
    		time.Sleep(time.Second * 2)
    	}
    }
    
    func g2(c chan bool,wg *sync.WaitGroup) {
    	i := 0
    	for{
    		select {
    		case <- c:
    			fmt.Printf("@@@---->>>>>g2  end<<<<<----+++
    ")
    			wg.Done()
    			return
    		default:
    			i++
    			fmt.Printf("+++>>>>>g2  working---%d---<<<<<+++
    ",i)
    		}
    		time.Sleep(time.Second * 2)
    	}
    }
    
    func g3(c chan bool,wg *sync.WaitGroup) {
    	i := 0
    	for{
    		select {
    		case <- c:
    			fmt.Printf("@@@---->>>>>g3  end<<<<<----+++
    ")
    			wg.Done()
    			return
    		default:
    			i++
    			fmt.Printf("+++>>>>>g3  working---%d---<<<<<+++
    ",i)
    		}
    		time.Sleep(time.Second * 2)
    	}
    }
    
    

    运行结果

    +++>>>>>g2  working---1---<<<<<+++
    +++>>>>>g1  working---1---<<<<<+++
    +++>>>>>g3  working---1---<<<<<+++
    +++>>>>>g2  working---2---<<<<<+++
    +++>>>>>g1  working---2---<<<<<+++
    +++>>>>>g3  working---2---<<<<<+++
    +++>>>>>g2  working---3---<<<<<+++
    +++>>>>>g1  working---3---<<<<<+++
    +++>>>>>g3  working---3---<<<<<+++
    +++>>>>>g2  working---4---<<<<<+++
    +++>>>>>g1  working---4---<<<<<+++
    +++>>>>>g3  working---4---<<<<<+++
    +++>>>>>g2  working---5---<<<<<+++
    +++>>>>>g3  working---5---<<<<<+++
    +++>>>>>g1  working---5---<<<<<+++
    @@@---->>>>>g2  end<<<<<----+++
    @@@---->>>>>g1  end<<<<<----+++
    @@@---->>>>>g3  end<<<<<----+++
    ++++>>>>all gorutine finish...<<<<++++
    
  • 相关阅读:
    gifplayer-可控制GIF动画图片播放和暂停jQuery插件
    ERROR 2003 (HY000): Can't connect to MySQL server on
    linux下重启nginx
    查看MySQL的当前存储引擎
    MySQL查看表占用空间大小
    使用Sequel Pro通过ssh远程连接MySQL出错:The SSH Tunnel has unexpectedly closed
    textview 内容从头开始显示
    SQL优化
    运营平台框架整理(内部用)
    线程的取消和关闭
  • 原文地址:https://www.cnblogs.com/Kingram/p/12615323.html
Copyright © 2020-2023  润新知