Go竞态条件

在Go中,当两个或多个goroutines尝试访问相同的资源时,就会发生竞态条件。这可能发生在变量在不考虑其他例程的情况下尝试读取和写入资源时。

Go竞态条件示例

package main  
import (  
   "sync"  
   "time"  
   "math/rand"  
   "fmt"  
)  
var wait sync.WaitGroup  
var count int  
func  increment(s string)  {  
   for i :=0;i<10;i++ {  
      x := count  
      x++;  
      time.Sleep(time.Duration(rand.Intn(4))*time.Millisecond)  
      count = x;  
      fmt.Println(s, i,"Count: ",count)  
        
   }  
   wait.Done()  
     
}  
func main(){  
   wait.Add(2)  
   go increment("foo: ")  
   go increment("bar: ")  
   wait.Wait()  
   fmt.Println("last count value " ,count)  
}  

输出:

foo:  0 Count:  1
bar:  0 Count:  1
foo:  1 Count:  2
foo:  2 Count:  3
foo:  3 Count:  4
bar:  1 Count:  2
foo:  4 Count:  5
foo:  5 Count:  6
foo:  6 Count:  7
bar:  2 Count:  3
bar:  3 Count:  4
bar:  4 Count:  5
foo:  7 Count:  8
foo:  8 Count:  9
bar:  5 Count:  6
bar:  6 Count:  7
foo:  9 Count:  10
bar:  7 Count:  8
bar:  8 Count:  9
bar:  9 Count:  10
last count value  10

正如您在上面的示例中所看到的,count资源被2个goroutine访问。每个例程迭代10次。在这种情况下,count变量应该最终为20。但事实并非如此,因为它模拟了竞态条件。

标签: Golang, Golang下载, Golang教程, Golang技术, Golang学习, Golang学习教程, Golang语言, Golang开发, Golang入门教程, Golang进阶教程, Golang高级教程, Golang面试题, Golang笔试题, Golang编程思想