golang 竞争状态

代码参考Go 语言实战 GO INACTION
//竞争状态;如果两个或者多个goroutine 在没有互相同步的情况下访问某个共享的资源,并试图读写这个资源,就处于相互竞争的状态,这种情况称作竞争状态

package main

import (
   "fmt"
   "runtime"
   "sync"
)

var(
   counter int
   wg sync.WaitGroup
)

func main()  {

   runtime.GOMAXPROCS(2)
   wg.Add(2)

   go incCounter(1)
   go incCounter(2)

   wg.Wait()
   fmt.Println("Final Counter:",counter)
}

func incCounter(id int)  {
   defer wg.Done()

   for count :=0;count<2;count++{
      value:=counter

      //runtime.Gosched()用于让出CPU时间片
      runtime.Gosched()

      value++

      counter=value
   }
}

猜你喜欢

转载自blog.csdn.net/weixin_40161254/article/details/82899033