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

hotfix: fix a race condition with RWMutex #23

Merged
merged 1 commit into from
Jan 21, 2024
Merged
Show file tree
Hide file tree
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
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ This release will include the following changes:

### IMPROVEMENTS

### BUG FIXES
### BUG FIXES
- Fix a race condition issue in the SIEVE cache. [\#23](https://github.com/scalalang2/golang-fifo/pull/23) by @scalalang2
18 changes: 9 additions & 9 deletions sieve/sieve.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type entry[K comparable, V any] struct {
}

type Sieve[K comparable, V any] struct {
lock sync.RWMutex
lock sync.Mutex
size int
items map[K]*list.Element
ll *list.List
Expand Down Expand Up @@ -48,8 +48,8 @@ func (s *Sieve[K, V]) Set(key K, value V) {
}

func (s *Sieve[K, V]) Get(key K) (value V, ok bool) {
s.lock.RLock()
defer s.lock.RUnlock()
s.lock.Lock()
defer s.lock.Unlock()
if e, ok := s.items[key]; ok {
e.Value.(*entry[K, V]).visited = true
return e.Value.(*entry[K, V]).value, true
Expand Down Expand Up @@ -78,15 +78,15 @@ func (s *Sieve[K, V]) Remove(key K) (ok bool) {
}

func (s *Sieve[K, V]) Contains(key K) (ok bool) {
s.lock.RLock()
defer s.lock.RUnlock()
s.lock.Lock()
defer s.lock.Unlock()
_, ok = s.items[key]
return
}

func (s *Sieve[K, V]) Peek(key K) (value V, ok bool) {
s.lock.RLock()
defer s.lock.RUnlock()
s.lock.Lock()
defer s.lock.Unlock()

if e, ok := s.items[key]; ok {
return e.Value.(*entry[K, V]).value, true
Expand All @@ -96,8 +96,8 @@ func (s *Sieve[K, V]) Peek(key K) (value V, ok bool) {
}

func (s *Sieve[K, V]) Len() int {
s.lock.RLock()
defer s.lock.RUnlock()
s.lock.Lock()
defer s.lock.Unlock()

return s.ll.Len()
}
Expand Down