GoAtomic

/ / GoAtomic

通过同步/原子程序包,原子变量用于管理状态并避免争用条件。原子计数器可以通过多个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

祝学习愉快! (发现内容有误?请选中要编辑的内容 -> 右键 -> 修改 -> 提交!帮助我们改进教程质量)

精选教程推荐

👇 以下精选教程可能对您有帮助,拓展您的技术视野

搞定音频技术 -〔冯建元 〕

如何读懂一首诗 -〔王天博〕

乔新亮的CTO成长复盘 -〔乔新亮〕

技术管理案例课 -〔许健〕

分布式系统案例课 -〔杨波〕

接口测试入门课 -〔陈磊〕

性能测试实战30讲 -〔高楼〕

TensorFlow快速入门与实战 -〔彭靖田〕

朱赟的技术管理课 -〔朱赟〕

📝 好记忆不如烂笔头,留下您的学习笔记吧!

暂无学习笔记,成为第一个分享的人吧!

您的笔记将帮助成千上万的学习者