Last active
June 15, 2020 01:09
-
-
Save pacuna/6abc7ac0c8a95feb4b42744c3089d1ad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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