package main
import (
"fmt"
"strconv"
"time"
)
type value struct {
id int
op int
ret chan int
}
var dic map[int]int
var ch chan *value
func readAndWrite2Map() {
for {
select{
case flag := - ch:
if flag.op > 0 {
log.Printf("id: %v, op: %v, ret: %v", flag.id, flag.op, flag.op)
dic[1] = flag.op
flag.ret - dic[1]
} else if flag.op == 0 {
log.Printf("id: %v, op: %v, ret: %v", flag.id, flag.op, dic[1])
flag.ret - dic[1]
} else {
return
}
}
}
}
func out(flag, i, val int) {
if flag == 0 {
fmt.Println(strconv.Itoa(i) + "th goroutine read the value is ", val)
} else {
fmt.Println(strconv.Itoa(i)+"th goroutine write to the map ", val)
}
}
func main() {
dic = make(map[int]int)
ch = make(chan *value)
dic[1] = -1
go readAndWrite2Map()
for i := 0; i = 5; i++ {
if (i % 2) == 0 {
go func(i int) {
var tmp value
for {
tmp.op = 0
ch - tmp
out(0, i, -tmp.ret)
time.Sleep(time.Millisecond)
}
}(i)
} else {
go func(i int) {
var tmp value
for {
tmp.op = i
ch - tmp
out(1, i, -tmp.ret)
time.Sleep(time.Millisecond)
}
}(i)
}
}
time.Sleep(time.Second * 60)
}