Understanding Golang Concurency
Golang's main selling point is that it manages multiple processes to speed up programs created in the language. The Golang programming language makes it easier for us to work with concurrency models.
Let's breakdown how to work with concurency in Go.
Goroutine
A goroutine is a lightweight thread managed by the Go runtime
Every go program will be executed inside goroutine, so here's an example how to launch a goroutine.
package main
func main() {
println("I'm inisde default goroutine")
}
By default if we create a go program with main
function and execute it, it will launch a go routine but it only one go routine. You can add more go routine by add go
before calling a function.
package main
func other_goroutine() {
println("I'm in other goroutine")
}
func main() {
go other_goroutine()
println("I'm inisde default goroutine")
}
Channel
Now that we have a multiple go routine we won't be able to work with the same data source in multiple go routine because it will lead to race condition. To fix this issue we can use channel to communicate between multiple go routine.
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan string)
go sender(c)
go ponger(c)
go receiver(c)
in := 0
fmt.Scanln(&in)
}
func sender(c chan <- string) {
for i := 0; i < 10; i++ {
c <- "money"
}
}
func ponger(c chan <- string) {
c <- "Money"
c <- "Debt"
}
func receiver(c <- chan string) {
for {
msg := <- c
fmt.Println(msg)
time.Sleep(time.Second * 1)
}
}