Improve code quality and thread safety (#844)
- Format Go files (gofmt) for backend/windows/notify*.go - Add thread safety to Stopwatch with sync.Mutex - Add comprehensive unit tests for Stopwatch with race detection - Add godoc comments to ImageCache public APIs - Improve IPC documentation with platform-specific socket path details - Document portable mode TODO for future enhancement
This commit is contained in:
@@ -1,14 +1,26 @@
|
||||
package util
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Stopwatch is a thread-safe timer for measuring elapsed time.
|
||||
// It can be started, stopped, and reset, and supports reading
|
||||
// the elapsed time while running or stopped.
|
||||
type Stopwatch struct {
|
||||
mu sync.Mutex
|
||||
running bool
|
||||
started time.Time
|
||||
elapsed time.Duration
|
||||
}
|
||||
|
||||
// Start begins or resumes the stopwatch.
|
||||
// If already running, this is a no-op.
|
||||
func (s *Stopwatch) Start() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.running {
|
||||
return
|
||||
}
|
||||
@@ -16,7 +28,12 @@ func (s *Stopwatch) Start() {
|
||||
s.running = true
|
||||
}
|
||||
|
||||
// Stop pauses the stopwatch and accumulates the elapsed time.
|
||||
// If already stopped, this is a no-op.
|
||||
func (s *Stopwatch) Stop() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if !s.running {
|
||||
return
|
||||
}
|
||||
@@ -24,7 +41,13 @@ func (s *Stopwatch) Stop() {
|
||||
s.running = false
|
||||
}
|
||||
|
||||
// Elapsed returns the total elapsed time.
|
||||
// If the stopwatch is running, includes time since last Start().
|
||||
// Safe to call concurrently with other methods.
|
||||
func (s *Stopwatch) Elapsed() time.Duration {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
e := s.elapsed
|
||||
if s.running {
|
||||
e += time.Since(s.started)
|
||||
@@ -32,7 +55,11 @@ func (s *Stopwatch) Elapsed() time.Duration {
|
||||
return e
|
||||
}
|
||||
|
||||
// Reset stops the stopwatch and clears the elapsed time.
|
||||
func (s *Stopwatch) Reset() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.running = false
|
||||
s.elapsed = time.Duration(0)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user