使用select外层函数控制goroutine

使用select在外层函数控制goroutine,以及通知goroutine进行优雅的退出

package main

import (
	"time"
	"fmt"
)
var quit = make(chan int, 1)
func foo1()  {
	go func() {
		i := 0
		for {
			select {
			case <-quit:
				fmt.Println("goroutine exit..")
				return
			default:
				fmt.Println(i)
				time.Sleep(time.Second * 1)
				i++
			}
		}
	}()
	fmt.Println("foo1 done")
}

func foo2()  {
	quit <- 1
	fmt.Println("foo2 done")
}

func main() {
	foo1()
	time.Sleep(5 * time.Second)
	foo2()
	time.Sleep(5 * time.Second)
	fmt.Println("main done")
}

屏幕输出:

foo1 done
0
1
2
3
4
foo2 done
goroutine exit..
main done

 第二种,通过time.After控制timeout,比第一种更优雅,屏幕输出通第一种一样

package main

import (
	"time"
	"fmt"
)
var quit = make(chan int, 1)
func foo1()  {
	go func() {
		i := 0
		for {
			select {
			case <- time.After(time.Second * 1):
				fmt.Println(i)
				i++

			case <-quit:
				fmt.Println("goroutine exit..")
				return
			//default:
			//	fmt.Println(i)
			//	i++
			}
		}
	}()
	fmt.Println("foo1 done")
}

func foo2()  {
	quit <- 1
	fmt.Println("foo2 done")
}

func main() {
	foo1()
	time.Sleep(5 * time.Second)
	foo2()
	time.Sleep(5 * time.Second)
	fmt.Println("main done")
}

  

posted on 2019-05-16 17:50  WalkerWang731  阅读(141)  评论(0编辑  收藏  举报

导航