Skip to content

Instantly share code, notes, and snippets.

@jacobgarcia
Created May 10, 2020 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacobgarcia/a07d92ff331404ea413d363cd6acc7d5 to your computer and use it in GitHub Desktop.
Save jacobgarcia/a07d92ff331404ea413d363cd6acc7d5 to your computer and use it in GitHub Desktop.
Channel counter implementation in Go without using sync.WaitGroup nor sync.Mutex. Only channels.
package main
import "sync/atomic"
func sum(counter *int32, i int32) *int32 {
atomic.AddInt32(counter, i)
return counter
}
func main() {
var counter int32
ch := make(chan *int32)
for i := 0; i < 1000; i++ {
go func(i int) {
ch <- sum(&counter, int32(i))
}(i)
}
for i := 0; i < 999; i++ {
_ = <-ch
}
println(*(<-ch))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment