Created
December 24, 2024 06:40
-
-
Save hackerchai/2fa68ec244506cd3183794dac7964030 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"sync" | |
"sync/atomic" | |
"testing" | |
) | |
// AtomicSafeString implements thread-safe string operations using atomic.Value | |
type AtomicSafeString struct { | |
value atomic.Value | |
} | |
func NewAtomicSafeString(initial string) *AtomicSafeString { | |
ss := &AtomicSafeString{} | |
ss.value.Store(initial) | |
return ss | |
} | |
func (ss *AtomicSafeString) Set(value string) { | |
ss.value.Store(value) | |
} | |
func (ss *AtomicSafeString) Get() string { | |
return ss.value.Load().(string) | |
} | |
// MutexSafeString implements thread-safe string operations using RWMutex | |
type MutexSafeString struct { | |
value string | |
mutex sync.RWMutex | |
} | |
func NewMutexSafeString(initial string) *MutexSafeString { | |
return &MutexSafeString{ | |
value: initial, | |
} | |
} | |
func (ss *MutexSafeString) Set(value string) { | |
ss.mutex.Lock() | |
defer ss.mutex.Unlock() | |
ss.value = value | |
} | |
func (ss *MutexSafeString) Get() string { | |
ss.mutex.RLock() | |
defer ss.mutex.RUnlock() | |
return ss.value | |
} | |
func BenchmarkSafeString(b *testing.B) { | |
// Test parameters | |
const ( | |
goroutines = 100 // Number of concurrent goroutines | |
writeRatio = 0.05 // Write operation ratio (5%) | |
) | |
// Benchmark Atomic implementation | |
b.Run("Atomic", func(b *testing.B) { | |
ss := NewAtomicSafeString("initial") | |
b.ResetTimer() | |
b.RunParallel(func(pb *testing.PB) { | |
for pb.Next() { | |
if float64(fastrand()%100)/100 < writeRatio { | |
// Write operation | |
ss.Set("new value") | |
} else { | |
// Read operation | |
_ = ss.Get() | |
} | |
} | |
}) | |
}) | |
// Benchmark RWMutex implementation | |
b.Run("RWMutex", func(b *testing.B) { | |
ss := NewMutexSafeString("initial") | |
b.ResetTimer() | |
b.RunParallel(func(pb *testing.PB) { | |
for pb.Next() { | |
if float64(fastrand()%100)/100 < writeRatio { | |
// Write operation | |
ss.Set("new value") | |
} else { | |
// Read operation | |
_ = ss.Get() | |
} | |
} | |
}) | |
}) | |
} | |
// fastrand returns a fast random number | |
var r uint32 | |
func fastrand() uint32 { | |
r = r*1664525 + 1013904223 | |
return r | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment