Go原子变量

原子变量通过sync/atomic包用于管理状态,避免竞态条件。原子计数器可以被多个goroutine访问。

Go原子变量示例

package main  
import (  
   "sync"  
   "time"  
   "math/rand"  
   "fmt"  
   "sync/atomic"  
)  
var wait sync.WaitGroup  
var count int64  
func increment(s string) {  
   for i := 0; i < 10; i++ {  
      time.Sleep(time.Duration((rand.Intn(3))) * time.Millisecond)  
      atomic.AddInt64(&count, 1)  
      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
foo:  1 Count -> 2
bar:  0 Count -> 3
bar:  1 Count -> 4
bar:  2 Count -> 5
foo:  2 Count -> 6
bar:  3 Count -> 7
bar:  4 Count -> 8
bar:  5 Count -> 9
foo:  3 Count -> 10
bar:  6 Count -> 11
bar:  7 Count -> 12
foo:  4 Count -> 13
foo:  5 Count -> 14
bar:  8 Count -> 15
bar:  9 Count -> 16
foo:  6 Count -> 17
foo:  7 Count -> 18
foo:  8 Count -> 19
foo:  9 Count -> 20
last count value  20

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