Skip to content

Instantly share code, notes, and snippets.

@pacuna
Last active June 15, 2020 01:09
Show Gist options
  • Save pacuna/6abc7ac0c8a95feb4b42744c3089d1ad to your computer and use it in GitHub Desktop.
Save pacuna/6abc7ac0c8a95feb4b42744c3089d1ad to your computer and use it in GitHub Desktop.
func (l *list) Add(item []byte) bool {
key, _ := hashstructure.Hash(item, nil)
l.head.lock()
pred := l.head
curr := pred.next
curr.lock()
// Displace locks during each iteration.
// We keep the lock for curr when unlocking pred.
// This way the coupled-lock is maintained
for curr.key < key {
pred.unlock()
pred = curr
curr = curr.next
curr.lock()
}
if curr.key == key {
pred.unlock()
curr.unlock()
return false
}
n := newNode(item)
n.next = curr
pred.next = n
l.mu.Lock()
l.size++
l.mu.Unlock()
curr.unlock()
pred.unlock()
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment