package main import ( "fmt" "sync" ) func main() { var rwMutex sync.RWMutex sharedData := "initial data" // write access rwMutex.Lock() sharedData = "updated data" rwMutex.Unlock() // read access rwMutex.RLock() fmt.Println("Shared data:", sharedData) rwMutex.RUnlock() }
package main import ( "fmt" "sync" ) func main() { var rwMutex sync.RWMutex sharedData := "initial data" // write access rwMutex.Lock() go func() { sharedData = "updated data 1" rwMutex.Unlock() }() go func() { sharedData = "updated data 2" rwMutex.Unlock() }() // wait for goroutines to complete rwMutex.Lock() // read access rwMutex.RLock() fmt.Println("Shared data:", sharedData) rwMutex.RUnlock() }This example demonstrates how the `RWMutex` type can be used to safely coordinate access to a shared resource by multiple goroutines. Two anonymous functions are created with the intention of updating `sharedData`. However, both are launched as goroutines so that they can run concurrently. Both functions acquire exclusive write access to the shared resource with `Lock` and update the value of `sharedData`. The second call to `Unlock` will block until the first goroutine completes its update and releases the lock. Once both goroutines have completed their updates and released the lock, the read access is allowed and the value of `sharedData` is printed. This package is a standard library provided by the Go programming language.