Last active
June 28, 2020 15:22
-
-
Save zigo101/338a7ae09d108171a677c38e93af2f39 to your computer and use it in GitHub Desktop.
Use sync.RWMutex to slice write jobs
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 | |
import ( | |
"fmt" | |
"math/rand" | |
"sync" | |
"time" | |
) | |
func main() { | |
rand.Seed(time.Now().UnixNano()) | |
const N = 9 | |
var vs = make([]int, N) | |
var rwm sync.RWMutex | |
for i := range [N]struct{}{} { | |
i := i | |
go func() { | |
time.Sleep(time.Second * time.Duration(rand.Intn(300)) / 100) | |
rwm.RLock() | |
defer rwm.RUnlock() | |
vs[i] = i + 1 | |
}() | |
} | |
for { | |
time.Sleep(time.Second / 20) | |
if ready := func() bool { | |
rwm.Lock() | |
defer rwm.Unlock() | |
k := 0 | |
for i := range [N]struct{}{} { | |
if vs[i] > 0 { | |
k++ | |
} | |
} | |
fmt.Println(vs) | |
return k == N | |
}(); ready { | |
break | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment