Skip to content
Myr

concurrent_set.go

This file

Path

src/util/concurrent_set.go

39 lines · 851 bytes · Go

Last changed by

Not known.

History of this file

Take it

1package util23import "sync"45// ConcurrentSet is a thread-safe set implementation.6type ConcurrentSet[T comparable] struct {7	lock  sync.RWMutex8	items map[T]struct{}9}1011// NewConcurrentSet creates a new ConcurrentSet.12func NewConcurrentSet[T comparable]() *ConcurrentSet[T] {13	return &ConcurrentSet[T]{14		items: make(map[T]struct{}),15	}16}1718// Add adds an item to the set.19func (s *ConcurrentSet[T]) Add(item T) {20	s.lock.Lock()21	defer s.lock.Unlock()22	s.items[item] = struct{}{}23}2425// Remove removes an item from the set.26func (s *ConcurrentSet[T]) Remove(item T) {27	s.lock.Lock()28	defer s.lock.Unlock()29	delete(s.items, item)30}3132// ForEach iterates over each item in the set and applies the provided function.33func (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}