Skip to content

Commit

Permalink
Fix race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
k1LoW committed Dec 4, 2024
1 parent f20acce commit b104406
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions stopw.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,12 @@ func New(ids ...any) *Span {

// New return a new breakdown span
func (s *Span) New(ids ...any) *Span {
s.mu.RLock()
if s.disable {
s.mu.RUnlock()
return s
}
s.mu.RUnlock()
if len(ids) == 0 {
s.mu.Lock()
n := &Span{
Expand Down Expand Up @@ -125,9 +128,12 @@ func (s *Span) New(ids ...any) *Span {

// IDs returns ID list
func (s *Span) IDs() []any {
s.mu.RLock()
if s.disable {
s.mu.RUnlock()
return nil
}
s.mu.RUnlock()
var ids []any
if s.parent != nil {
ids = s.parent.IDs()
Expand All @@ -139,27 +145,36 @@ func (s *Span) IDs() []any {

// Start stopwatch of span
func (s *Span) Start(ids ...any) *Span {
s.mu.RLock()
if s.disable {
s.mu.RUnlock()
return s
}
s.mu.RUnlock()
start := time.Now()
return s.StartAt(start, ids...)
}

// Stop stopwatch of span
func (s *Span) Stop(ids ...any) {
s.mu.RLock()
if s.disable {
s.mu.RUnlock()
return
}
s.mu.RUnlock()
end := time.Now()
s.StopAt(end, ids...)
}

// StartAt start stopwatch of span by specifying the time
func (s *Span) StartAt(start time.Time, ids ...any) *Span {
s.mu.RLock()
if s.disable {
s.mu.RUnlock()
return s
}
s.mu.RUnlock()
if len(ids) == 0 {
s.Reset()
}
Expand All @@ -172,9 +187,12 @@ func (s *Span) StartAt(start time.Time, ids ...any) *Span {

// StopAt stop stopwatch of span by specifying the time
func (s *Span) StopAt(end time.Time, ids ...any) {
s.mu.RLock()
if s.disable {
s.mu.RUnlock()
return
}
s.mu.RUnlock()
t, err := s.findByIDs(ids...)
if err != nil {
return
Expand All @@ -187,19 +205,25 @@ func (s *Span) StopAt(end time.Time, ids ...any) {

// Reset measurement result of span
func (s *Span) Reset() {
s.mu.RLock()
if s.disable {
s.mu.RUnlock()
return
}
s.mu.RUnlock()
s.StartedAt = time.Time{}
s.StoppedAt = time.Time{}
s.parent = nil
s.Breakdown = nil
}

func (s *Span) Elapsed() time.Duration {
s.mu.RLock()
if s.disable {
s.mu.RUnlock()
return 0
}
s.mu.RUnlock()
if s.StartedAt.IsZero() || s.StoppedAt.IsZero() {
return 0
}
Expand All @@ -208,12 +232,16 @@ func (s *Span) Elapsed() time.Duration {

// Disable stopwatch
func (s *Span) Disable() *Span {
s.mu.Lock()
defer s.mu.Unlock()
s.disable = true
return s
}

// Enable stopwatch
func (s *Span) Enable() *Span {
s.mu.Lock()
defer s.mu.Unlock()
s.disable = false
return s
}
Expand Down

0 comments on commit b104406

Please sign in to comment.