Created
October 25, 2018 14:58
-
-
Save qtopie/60b809c9389fcd0ddfe69ff665668eb1 to your computer and use it in GitHub Desktop.
Read-Write Lock in Go
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 | |
// Just a sample code for learning mutex. Don't use this code for prodution. | |
import ( | |
"fmt" | |
"sync" | |
"time" | |
) | |
type Account struct { | |
sync.RWMutex | |
balance int | |
} | |
func (acc *Account) Update(amount int) int { | |
acc.Lock() | |
defer acc.Unlock() | |
acc.balance += amount | |
// if write operation is pretty fast (fast like there's no write operation at all), the performace of using read-write lock is approximate to simple lock | |
time.Sleep(200 * time.Millisecond) | |
return acc.balance | |
} | |
func (acc *Account) Get() int { | |
acc.RLock() | |
defer acc.RUnlock() | |
time.Sleep(800 * time.Millisecond) | |
return acc.balance | |
} | |
func main() { | |
account := Account{ | |
balance: 100, | |
} | |
var wg sync.WaitGroup | |
start := time.Now() | |
// try to modify k to 2 to see what will happen | |
// k:=2 | |
k := 10 | |
for i := 0; i < 100; i++ { | |
if i%k == 0 { | |
wg.Add(1) | |
go func(n int) { | |
defer wg.Done() | |
fmt.Println("Writing", account.Update(n/10)) | |
}(i) | |
} else { | |
wg.Add(1) | |
// rw lock is good for reading | |
go func() { | |
defer wg.Done() | |
fmt.Println("Reading", account.Get()) | |
}() | |
} | |
} | |
wg.Wait() | |
end := time.Now() | |
fmt.Println("Duration", end.Sub(start)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment