github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/app/bconcurrent/orderly.go (about)

     1  package bconcurrent
     2  
     3  import "sync"
     4  
     5  type WaitGroup interface {
     6  	Add(int)
     7  	Wait()
     8  	Done()
     9  	Do()
    10  }
    11  
    12  type OrderlyTask struct {
    13  	sync.WaitGroup
    14  	fn func()
    15  }
    16  
    17  // Do 执行任务
    18  func (o *OrderlyTask) Do() {
    19  	o.Add(1)
    20  	go func() {
    21  		defer o.Done()
    22  		o.fn()
    23  	}()
    24  }
    25  
    26  // NewOrderTask 初始化任务
    27  func NewOrderTask(fn func()) *OrderlyTask {
    28  	return &OrderlyTask{
    29  		fn: fn,
    30  	}
    31  }
    32  
    33  // Orderly 顺序执行
    34  func Orderly(tasks []*OrderlyTask) {
    35  	for _, task := range tasks {
    36  		task.Do()
    37  		task.Wait()
    38  	}
    39  }