Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add mechanism to wait for items to be processed. #184

Merged
merged 2 commits into from
Aug 24, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ type Item struct {
Value interface{}
Cost int64
Expiration time.Time
wg *sync.WaitGroup
}

// NewCache returns a new Cache instance and any configuration errors, if any.
Expand Down Expand Up @@ -169,6 +170,16 @@ func NewCache(config *Config) (*Cache, error) {
return cache, nil
}

func (c *Cache) Wait() {
if c == nil {
return
}
wg := &sync.WaitGroup{}
wg.Add(1)
c.setBuf <- &Item{wg: wg}
wg.Wait()
}

// Get returns the value (if any) and a boolean representing whether the
// value was found or not. The value can be nil and the boolean can be true at
// the same time.
Expand Down Expand Up @@ -346,6 +357,10 @@ func (c *Cache) processItems() {
for {
select {
case i := <-c.setBuf:
if i.wg != nil {
i.wg.Done()
continue
}
// Calculate item cost value if new or update.
if i.Cost == 0 && c.cost != nil && i.flag != itemDelete {
i.Cost = c.cost(i.Value)
Expand Down