gitee.com/woood2/luca@v1.0.4/internal/cache/protector.go (about)

     1  package cache
     2  
     3  import (
     4  	"sync"
     5  	"time"
     6  )
     7  
     8  const (
     9  	releaseDelay = 50 * time.Millisecond
    10  )
    11  
    12  type Protector struct {
    13  	lock  sync.Mutex
    14  	apply map[string]chan struct{}
    15  }
    16  
    17  func (p *Protector) ApplyToSet(k string) (ok bool, ch chan struct{}, e error) {
    18  	p.lock.Lock()
    19  	defer p.lock.Unlock()
    20  
    21  	v, ex := p.apply[k]
    22  	if !ex {
    23  		newCh := make(chan struct{})
    24  		p.apply[k] = newCh
    25  		return true, newCh, nil
    26  	}
    27  	return false, v, nil
    28  }
    29  
    30  func (p *Protector) Release(k string) error {
    31  	time.AfterFunc(releaseDelay, func() {
    32  		p.lock.Lock()
    33  		defer p.lock.Unlock()
    34  
    35  		delete(p.apply, k)
    36  	})
    37  	return nil
    38  }