Previously in Golang Concurrency we talked about how goroutines in Go language works. Today we will focus on providing robustness to our previous talk by using semaphores from Golang sync package.
Here is redone example from our previous blogpost
Results may vary from machine to machine as. But in essence what we did is, we imported sync
package. sync
package contains WaitGroup
type, we declared variable wait
to be of WaitGroup type. Waitgroup
provides three methods namely Add
, Done
and Wait
.
1.) Add
method takes integer as a parameter delta to the counter, and once counter becomes zero, all blocking goroutines, waiting onto counter would be released. We provided no of goroutines we are going to wait upon
2.) Wait
methods waits for semaphore counter to become zero, before releasing goroutines, waiting onto other goroutines to terminate/finish. Our main program is waiting for other goroutines to finish.
3.) Done
method basically indicates that current goroutine, in which this is being called is done/finished, while decrementing semaphore counter. Our goroutines calls to Done
method indicating that goroutine is done executing its task.
Happy Going!
About The Author
I am Pankaj Baagwan, a System Design Architect. A Computer Scientist by heart, process enthusiast, and open source author/contributor/writer. Advocates Karma. Love working with cutting edge, fascinating, open source technologies.
To consult Pankaj Bagwan on System Design, Cyber Security and Application Development, SEO and SMO, please reach out at me[at]bagwanpankaj[dot]com
For promotion/advertisement of your services and products on this blog, please reach out at me[at]bagwanpankaj[dot]com
Stay tuned <3. Signing off for RAAM