Created
May 10, 2020 13:55
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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