github.com/sunvim/utils@v0.1.0/priorityqueue/waiters.go (about)

     1  package priorityqueue
     2  
     3  import "sync"
     4  
     5  type sema struct {
     6  	ready    chan bool
     7  	response *sync.WaitGroup
     8  }
     9  
    10  func newSema() *sema {
    11  	return &sema{
    12  		ready:    make(chan bool, 1),
    13  		response: &sync.WaitGroup{},
    14  	}
    15  }
    16  
    17  type waiters []*sema
    18  
    19  func (w *waiters) get() *sema {
    20  	if len(*w) == 0 {
    21  		return nil
    22  	}
    23  
    24  	sema := (*w)[0]
    25  	copy((*w)[0:], (*w)[1:])
    26  	(*w)[len(*w)-1] = nil // or the zero value of T
    27  	*w = (*w)[:len(*w)-1]
    28  	return sema
    29  }
    30  
    31  func (w *waiters) put(sema *sema) {
    32  	*w = append(*w, sema)
    33  }
    34  
    35  func (w *waiters) remove(sema *sema) {
    36  	if len(*w) == 0 {
    37  		return
    38  	}
    39  	// build new slice, copy all except sema
    40  	ws := *w
    41  	newWs := make(waiters, 0, len(*w))
    42  	for i := range ws {
    43  		if ws[i] != sema {
    44  			newWs = append(newWs, ws[i])
    45  		}
    46  	}
    47  	*w = newWs
    48  }