Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var mut sync.RWMutex
var wg sync.WaitGroup
wg.Add(5)
go func() {
defer wg.Done()
fmt.Println("reader #1 started")
mut.RLock()
fmt.Println("reader #1 locked")
defer mut.RUnlock()
defer fmt.Println("reader #1 unlocked")
time.Sleep(1000 * time.Millisecond)
}()
time.Sleep(50 * time.Millisecond)
go func() {
defer wg.Done()
fmt.Println("writer started")
mut.Lock()
fmt.Println("writer locked")
defer mut.Unlock()
defer fmt.Println("writer unlocked")
time.Sleep(500 * time.Millisecond)
}()
time.Sleep(50 * time.Millisecond)
go func() {
defer wg.Done()
fmt.Println("reader #3 started")
mut.RLock()
fmt.Println("reader #3 locked")
defer mut.RUnlock()
defer fmt.Println("reader #3 unlocked")
time.Sleep(1000 * time.Millisecond)
}()
time.Sleep(50 * time.Millisecond)
go func() {
defer wg.Done()
fmt.Println("reader #4 started")
mut.RLock()
fmt.Println("reader #4 locked")
defer mut.RUnlock()
defer fmt.Println("reader #4 unlocked")
time.Sleep(1000 * time.Millisecond)
}()
time.Sleep(50 * time.Millisecond)
go func() {
defer wg.Done()
fmt.Println("reader #2 started")
mut.RLock()
fmt.Println("reader #2 locked")
defer mut.RUnlock()
defer fmt.Println("reader #2 unlocked")
time.Sleep(1000 * time.Millisecond)
}()
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment