Skip to content

Instantly share code, notes, and snippets.

@hauxe
Created June 21, 2018 06:44
Show Gist options
  • Save hauxe/e503c82527d0f2b8bb94714096e0a735 to your computer and use it in GitHub Desktop.
Save hauxe/e503c82527d0f2b8bb94714096e0a735 to your computer and use it in GitHub Desktop.
// Compete compete for resource
func (mux *GreedyMutex) Compete(ctx context.Context, resource interface{}) {
mux.Lock()
greedyEntities := []PrioritizedEntity{}
defer func() { go mux.Compete(ctx, resource) }()
defer mux.Unlock()
defer func() {
var winner PrioritizedEntity
for _, entity := range greedyEntities {
if winner == nil || winner.GetPriority() < entity.GetPriority() {
winner = entity
}
}
if winner != nil {
winner.AccessResource(resource)
}
}()
// wait until have a request for resource
entity := <-mux.queue
greedyEntities = append(greedyEntities, entity)
c := time.NewTicker(mux.TimeToWait)
for {
select {
case <-ctx.Done():
return
case <-c.C:
c.Stop()
return
case entity := <-mux.queue:
greedyEntities = append(greedyEntities, entity)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment