Created
August 8, 2019 06:56
-
-
Save ilhamarrouf/0d9de9b26f8daed1988c37f354a8f6cd to your computer and use it in GitHub Desktop.
Stateful Goroutines
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/atomic" | |
"time" | |
) | |
type readOp struct { | |
key int | |
resp chan int | |
} | |
type writeOp struct { | |
key int | |
val int | |
resp chan bool | |
} | |
func main() { | |
var readOps uint64 | |
var writeOps uint64 | |
reads := make(chan readOp) | |
writes := make(chan writeOp) | |
go func() { | |
var state = make(map[int]int) | |
for { | |
select { | |
case read := <-reads: | |
read.resp <- state[read.key] | |
case write := <-writes: | |
state[write.key] = write.val | |
write.resp <- true | |
} | |
} | |
}() | |
for r := 0; r < 100; r++ { | |
go func() { | |
for { | |
read := readOp{ | |
key: rand.Intn(5), | |
resp: make(chan int)} | |
reads <- read | |
<-read.resp | |
atomic.AddUint64(&readOps, 1) | |
time.Sleep(time.Millisecond) | |
} | |
}() | |
} | |
for w := 0; w < 10; w++ { | |
go func() { | |
for { | |
write := writeOp{ | |
key: rand.Intn(5), | |
val: rand.Intn(100), | |
resp: make(chan bool)} | |
writes <- write | |
<-write.resp | |
atomic.AddUint64(&writeOps, 1) | |
time.Sleep(time.Millisecond) | |
} | |
}() | |
} | |
time.Sleep(time.Second) | |
readOpsFinal := atomic.LoadUint64(&readOps) | |
fmt.Println("readOps:", readOpsFinal) | |
writeOpsFinal := atomic.LoadUint64(&writeOps) | |
fmt.Println("writeOps:", writeOpsFinal) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment