go 协程之WaitGroup超时控制

package main

import (
	"fmt"
	"sync"
	"time"
)

// 调用示例
func main() {
	var w = sync.WaitGroup{}
	var ch = make(chan bool)
	w.Add(2)
	go func() {
		time.Sleep(time.Second * 2)
		fmt.Println("我2秒")
		w.Done()
	}()
	go func() {
		time.Sleep(time.Second * 6)
		fmt.Println("我6秒")
		w.Done()
	}()
	go func() {
		w.Wait()
		ch <- false
	}()

	select {
	case <-time.After(time.Second * 7):
		fmt.Println("我超时了")
	case <-ch:
		fmt.Println("我结束了")
	}
}

  

上一篇:Go语言之面向对象编程(三)


下一篇:Go 字符串与字符编码