zoukankan      html  css  js  c++  java
  • 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...<<<<++++
    
  • 相关阅读:
    app卡顿问题检测--KMCGeigerCounter
    报错---[UIApplication _runWithMainScene:transitionContext:completion:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3505.16/UIApplication.m:3294**
    键盘工具栏的快速集成--IQKeyboardManager
    iOS 对网络视频采集视频截图
    iOS-label出现未知边框线的bug
    iOS开发中图片方向的获取与更改
    通过代码设置button中文字的对齐方式
    util.date
    统计字符串每个字母的个数
    异常处理之多重catch
  • 原文地址:https://www.cnblogs.com/Kingram/p/12615323.html
Copyright © 2011-2022 走看看