| 1 |
package util |
| 2 |
|
| 3 |
import "sync" |
| 4 |
|
| 5 |
// ConcurrentSet is a thread-safe set implementation. |
| 6 |
type ConcurrentSet[T comparable] struct { |
| 7 |
lock sync.RWMutex |
| 8 |
items map[T]struct{} |
| 9 |
} |
| 10 |
|
| 11 |
// NewConcurrentSet creates a new ConcurrentSet. |
| 12 |
func NewConcurrentSet[T comparable]() *ConcurrentSet[T] { |
| 13 |
return &ConcurrentSet[T]{ |
| 14 |
items: make(map[T]struct{}), |
| 15 |
} |
| 16 |
} |
| 17 |
|
| 18 |
// Add adds an item to the set. |
| 19 |
func (s *ConcurrentSet[T]) Add(item T) { |
| 20 |
s.lock.Lock() |
| 21 |
defer s.lock.Unlock() |
| 22 |
s.items[item] = struct{}{} |
| 23 |
} |
| 24 |
|
| 25 |
// Remove removes an item from the set. |
| 26 |
func (s *ConcurrentSet[T]) Remove(item T) { |
| 27 |
s.lock.Lock() |
| 28 |
defer s.lock.Unlock() |
| 29 |
delete(s.items, item) |
| 30 |
} |
| 31 |
|
| 32 |
// ForEach iterates over each item in the set and applies the provided function. |
| 33 |
func (s *ConcurrentSet[T]) ForEach(fn func(item T)) { |
| 34 |
s.lock.RLock() |
| 35 |
defer s.lock.RUnlock() |
| 36 |
for item := range s.items { |
| 37 |
fn(item) |
| 38 |
} |
| 39 |
} |