Go by Example - Atomic Counters
Go by Example
Go is an open source programming language designed for building simple, fast, and reliable software.
Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.
Go by Example: Atomic Counters
golang管理状态的主要机制是通过channel的通信,可以通过之前的worker pools的例子看到。还有一些其他的管理状态的方式,这次我们探究一下sync/atomic包中的可以被多个goroutine访问的atomic counters.
1 | package main |
1 | tashuo:golang ta_shuo$ go run atomic-counter.go |
运行该程序,通过返回值可得知计数器累加了大概40000多次