To implement read-write locks for concurrent read and write access in Golang using sync.RWMutex
, you can follow these steps:
Step 1: Import the necessary package.
import "sync"
Step 2: Initialize an instance of sync.RWMutex
.
var rwMutex sync.RWMutex
Step 3: Use the Lock()
method of sync.RWMutex
to acquire a write lock before modifying the shared resource.
rwMutex.Lock()
defer rwMutex.Unlock()
// Write/modify the shared resource here
Step 4: Use the RLock()
method of sync.RWMutex
to acquire a read lock before reading from the shared resource.
rwMutex.RLock()
defer rwMutex.RUnlock()
// Read from the shared resource here
Step 5: With the write lock acquired by one goroutine, all other goroutines trying to acquire a write lock will be blocked until the lock is released. However, multiple goroutines can simultaneously acquire read locks and read from the shared resource concurrently.
Here's an example illustrating the usage:
package main
import (
"fmt"
"sync"
)
var (
rwMutex sync.RWMutex
sharedResource int
)
func writeData(value int) {
rwMutex.Lock()
defer rwMutex.Unlock()
// Write/modify the shared resource
sharedResource = value
fmt.Printf("Data written: %d\n", value)
}
func readData() {
rwMutex.RLock()
defer rwMutex.RUnlock()
// Read from the shared resource
fmt.Printf("Data read: %d\n", sharedResource)
}
func main() {
// Writing data
go writeData(10)
go writeData(20)
// Reading data
go readData()
go readData()
// Wait for goroutines to finish execution
time.Sleep(1 * time.Second)
}
In the above example, the writeData
function modifies the sharedResource
while holding a write lock, and the readData
function reads from the sharedResource
while holding a read lock. Multiple goroutines can concurrently read from the sharedResource
, but only one goroutine can write to it at a time, ensuring data consistency.