Skip to content

Commit

Permalink
chore: improve NewSingleton
Browse files Browse the repository at this point in the history
  • Loading branch information
sysulq committed Sep 10, 2024
1 parent 2ba3ef6 commit ffd4f0f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
8 changes: 2 additions & 6 deletions Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,8 @@ tasks:

build:gowork:
run: once
sources:
- /ext
- /tests
generates:
- go.work
- go.work.sum
status:
- test -f ../go.work || test -f go.work
cmds:
- go work init
- go work use -r .
Expand Down
11 changes: 8 additions & 3 deletions internal/singleton/singleton.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
// Singleton[T any] provides a common structure for components,
type Singleton[T any] struct {
instances map[string]*T
mu sync.Mutex
mu sync.RWMutex
}

// NewSingleton creates a new Singleton[T].
Expand All @@ -19,15 +19,20 @@ func NewSingleton[T any]() *Singleton[T] {

// Get returns the instance of the component with the given name.
func (s *Singleton[T]) Get(name string, initFn func() *T) *T {
s.mu.Lock()
defer s.mu.Unlock()
s.mu.RLock()

if instance, exists := s.instances[name]; exists {
s.mu.RUnlock()
return instance
}

s.mu.RUnlock()

instance := initFn()

s.mu.Lock()
s.instances[name] = instance
s.mu.Unlock()

return instance
}

0 comments on commit ffd4f0f

Please sign in to comment.