代码没有对全局变量加锁,不会出现线程安全问题吗?
来源:49-7 sentinel的熔断接口-基于错误数

曹学习
2021-06-09
go func() {
for {
total++
e, b := sentinel.Entry("abc")
if b != nil {
// goroutine1 阻塞
totalBlock++
fmt.Println("协程熔断了")
time.Sleep(time.Duration(rand.Uint64()%20) * time.Millisecond)
} else {
totalPass++
if rand.Uint64()%20 > 9 {
totalErr++
// 将当前调用记录为错误。
sentinel.TraceError(e, errors.New("biz error"))
}
// goroutine1 通过
time.Sleep(time.Duration(rand.Uint64()%50+10) * time.Millisecond)
e.Exit()
}
}
}()
go func() {
for {
total++
e, b := sentinel.Entry("abc")
if b != nil {
// goroutine2 阻塞
totalBlock++
time.Sleep(time.Duration(rand.Uint64()%20) * time.Millisecond)
} else {
// goroutine2 通过
totalPass++
time.Sleep(time.Duration(rand.Uint64()%80) * time.Millisecond)
e.Exit()
}
}
}()
这两个协程都是直接操作total,totalBlock,totalPass。在不加锁的情况下,会出现重写等线程安全问题吧
写回答
1回答
-
bobby
2021-06-11
如果是多线程操作的话,由于可能会被中断,所以有可能会出现同步问题,但是如果是协程,因为python的协程调度不会在执行这种操作的时候被中断,不会出现这种问题
00
相似问题