Skip to content

Commit

Permalink
Fix race condition for concurrent usage
Browse files Browse the repository at this point in the history
* Mutex removed and only RWMutex is used for concurrency.

* README updated.

Signed-off-by: Gökhan Özeloğlu <gozeloglu@gmail.com>
  • Loading branch information
gozeloglu committed Mar 28, 2022
1 parent b74a37d commit 5e5e665
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 14 deletions.
7 changes: 2 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
# set
[![Go Reference](https://pkg.go.dev/badge/github.com/gozeloglu/set.svg)](https://pkg.go.dev/github.com/gozeloglu/set)
[![Go Report Card](https://goreportcard.com/badge/github.com/gozeloglu/set)](https://goreportcard.com/report/github.com/gozeloglu/set)
[![GoCover](http://gocover.io/_badge/github.com/gozeloglu/set)](http://gocover.io/github.com/gozeloglu/set)
----
# set [![Go Reference](https://pkg.go.dev/badge/github.com/gozeloglu/set.svg)](https://pkg.go.dev/github.com/gozeloglu/set) [![Go Report Card](https://goreportcard.com/badge/github.com/gozeloglu/set)](https://goreportcard.com/report/github.com/gozeloglu/set) [![GoCover](http://gocover.io/_badge/github.com/gozeloglu/set)](http://gocover.io/github.com/gozeloglu/set)

`set` is a data structure package written by **Go**. It provides some basic set functionalities of the user. It uses
`map` data structure under the hood.

Expand Down
17 changes: 8 additions & 9 deletions threadsafe.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import "sync"
// ThreadSafeSet is a set type which provides the thread-safety.
type ThreadSafeSet struct {
set map[interface{}]struct{}
mu sync.Mutex
rw sync.RWMutex
}

Expand All @@ -16,8 +15,8 @@ func newThreadSafeSet() *ThreadSafeSet {

// Add adds a new values to set.
func (s *ThreadSafeSet) Add(val interface{}) {
s.mu.Lock()
defer s.mu.Unlock()
s.rw.Lock()
defer s.rw.Unlock()
s.add(val)
}

Expand All @@ -29,17 +28,17 @@ func (s *ThreadSafeSet) add(val interface{}) {

// Append adds multiple values into set.
func (s *ThreadSafeSet) Append(values ...interface{}) {
s.mu.Lock()
defer s.mu.Unlock()
s.rw.Lock()
defer s.rw.Unlock()
for _, val := range values {
s.add(val)
}
}

// Remove deletes the given value.
func (s *ThreadSafeSet) Remove(val interface{}) {
s.mu.Lock()
defer s.mu.Unlock()
s.rw.Lock()
defer s.rw.Unlock()
delete(s.set, val)
}

Expand Down Expand Up @@ -83,8 +82,8 @@ func (s *ThreadSafeSet) Pop() interface{} {

// Clear removes everything from the set.
func (s *ThreadSafeSet) Clear() {
s.mu.Lock()
defer s.mu.Unlock()
s.rw.Lock()
defer s.rw.Unlock()
s.set = make(map[interface{}]struct{})
}

Expand Down

0 comments on commit 5e5e665

Please sign in to comment.