关于sync.RWMutex读写锁的问题

yanyiwu · · 2890 次点击
很好,其实我也是这么想的。
#2
更多评论
polaris
社区,需要你我一同完善!
并发程序结果具有不可预测性,而且,并不是说不安全程序就得挂掉。即使一次运行,结果没有问题,也不代表真的没有问题。你这个代码是有问题的。
#1
读写是独立没有问题的,同时写才有不同步的问题,上面的代码有几个问题: 1. for里需要使用Gosched让出时间片 2. 最后的for使的程序根本不会停下来 并发的情况一般建议先考虑chan,再考虑sync ```golang package main import ( "fmt" "math/rand" "runtime" "time" ) type Tmp struct { a int b string c float64 } var g Tmp func main() { runtime.GOMAXPROCS(4) rand.Seed(time.Now().Unix()) g = Tmp{rand.Intn(100), "123", rand.Float64()} go func() { for { g.c = rand.Float64() fmt.Println("set", g.c) runtime.Gosched() } }() go func() { for { fmt.Println("get", g.c) runtime.Gosched() } }() time.Sleep(30 * time.Second) } ```
#3