go用chan实现WaitGroup并支持超时

来来来,话不多说,上代码

package main

import "fmt"
import "time"
import "sync"

type group struct {
	gc chan bool
	tk *time.Ticker
	cap int
	mutex sync.Mutex
}

func WaitGroup(timeOuteRec int) *group{
	timeout     := time.Millisecond * time.Duration(timeOuteRec)
	wg := group{
		gc   : make(chan bool),
		cap  :  0,
		tk   : time.NewTicker(timeout),
	}

	return &wg
}


func(w *group)Add(index int){
	w.mutex.Lock()
	w.cap++
	w.mutex.Unlock()

	go func(w *group,index int) {
		for i := 0;i<index;i++{
			fmt.Println("exec goruntine product")
			w.gc<- true
		}
	}(w,index)
}

func(w *group)Done(){
	<-w.gc
	fmt.Println("exec goruntine consumer")
	w.mutex.Lock()
	w.cap--
	w.mutex.Unlock()
}

func(w *group)Wait(){
	defer w.tk.Stop()
	for  {
		select {
		case <-w.tk.C:
			fmt.Println("time out exec over")
			return;
		default:
			w.mutex.Lock()
			if w.cap == 0 {
				fmt.Println("all goruntine exec over")
				return;
			}
			w.mutex.Unlock()
		}
	}
}

func main() {
	fmt.Println("start...")
	wg := WaitGroup(10)
	wg.Add(1)
	closer := func(wg *group) {
		wg.Done()
	}
	go closer(wg)

	wg.Wait()
	fmt.Println("exec return")
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值