gitee.com/h79/goutils@v1.22.10/common/queue/run.go (about)

     1  package queue
     2  
     3  import (
     4  	"gitee.com/h79/goutils/common/system"
     5  	"sync"
     6  	"time"
     7  )
     8  
     9  type Call struct {
    10  	PopCount int
    11  	Duration time.Duration
    12  	Wait     func(dur time.Duration)
    13  	Begin    func(count int) any
    14  	Process  func(be any, data any)
    15  	Quited   func(lock sync.Locker, qu Queue)
    16  }
    17  
    18  func Run(c Call, lock sync.Locker, qu Queue) {
    19  	var count int
    20  	var popCount = c.PopCount
    21  	if popCount <= 0 {
    22  		popCount = 10
    23  	}
    24  	if c.Wait == nil {
    25  		c.Wait = func(dur time.Duration) {
    26  			time.Sleep(dur)
    27  		}
    28  	}
    29  	if c.Quited == nil {
    30  		c.Quited = func(lock sync.Locker, qu Queue) {
    31  		}
    32  	}
    33  	ten := make([]any, popCount)
    34  	for {
    35  		count = 0
    36  		lock.Lock()
    37  		for i := 0; i < popCount; i++ {
    38  			v := qu.Pop()
    39  			if v == nil {
    40  				break
    41  			}
    42  			ten[i] = v
    43  			count++
    44  		}
    45  		lock.Unlock()
    46  		var bn = c.Begin(count)
    47  		for i := 0; i < count; i++ {
    48  			c.Process(bn, ten[i])
    49  		}
    50  		c.Wait(c.Duration)
    51  
    52  		select {
    53  		case <-system.Closed():
    54  			c.Quited(lock, qu)
    55  			return
    56  		default:
    57  		}
    58  	}
    59  }