type cond struct{
sema1 int32
sema2 int32
}
func (c *cond)printA(){
for {
if c.sema1==0{
println("A")
atomic.CompareAndSwapInt32(&c.sema1,0,1)
}
}
}
func (c *cond)printB(){
for {
if c.sema1==1&& c.sema2==0{
println("B")
atomic.CompareAndSwapInt32(&c.sema2,0,1)
}
}
}
func (c *cond) printC(){
for {
if c.sema2==1 {
println("C")
println("--------------------------------")
atomic.CompareAndSwapInt32(&c.sema1, 1, 0)
atomic.CompareAndSwapInt32(&c.sema2, 1, 0)
}
}
}
func main() {
var con =new (cond)
con.sema1=0
con.sema2=0
go con.printC()
go con.printB()
go con.printA()
time.Sleep(5*time.Second)
}
![image.png](https://static.studygolang.com/210305/7e88e82bc250a4682f7fda65d71aba5b.png)
![image.png](https://static.studygolang.com/210305/c9b5cdd827dfa8aed6ccf75161d33bd7.png)
printC的时候,有两个参数进行交换,没有对其顺序操作进行加锁,导致多goroutine进行对行抢占,你对流程加锁后就可以避免错误,具体的调试你需要自己进行
#1