To safely share data between Goroutines using sync.Mutex, you can follow the steps below:
Step 1: Define a struct that represents the shared data and create a Mutex variable for synchronization:
type SharedData struct {
value int
mutex sync.Mutex
}
Step 2: Implement getter and setter methods for accessing and modifying the shared data:
func (s *SharedData) GetValue() int {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.value
}
func (s *SharedData) SetValue(newValue int) {
s.mutex.Lock()
defer s.mutex.Unlock()
s.value = newValue
}
Step 3: Use the getter and setter methods in Goroutines to access and modify the shared data safely:
func main() {
sharedData := &SharedData{}
// In one Goroutine
go func() {
sharedData.SetValue(42)
}()
// In another Goroutine
go func() {
value := sharedData.GetValue()
fmt.Println(value)
}()
time.Sleep(time.Second)
}
By using sync.Mutex and the Lock/Unlock methods, the shared data access is properly synchronized, ensuring that only one Goroutine can access it at a time.
Note: Be cautious when using Mutex. Avoid deadlocks by always releasing the lock using defer or explicit Unlock() calls.