Concurrency in go
-Do not communicate by sharing memory; instead, share memory by communicating
-Do not communicate by locking variables between threads
-Communicate by sending values from one concurrent piece of code to another
Do not Communicate by Sharing Memoey
- Do not communicate by locking variables between threads
Share Memory by Communicating
- Communicate by sending values from one concurrent piece of code to another
- Thread 1 will wait for thread 2 to receive the value before they continue execution
Goroutines
- Lightweight "threads"
- Goroutines are multiplexed onto multiple OS threads
- Some Goroutines can even run on the same thread
- Go's runtime takes care of the complexity
- activated by the "go" keyword, syntax: go f(x,y,z)
func main() {
go waitAndSay("World")
fmt.Println("Hello")
time.Sleep(3 * time.Second)
}
func waitAndSay(s string) {
time.Sleep(2 * time.Second)
fmt.Println(s)
}
- After printing "Hello", main function is waiting for 3 seconds.
- So 2 second after, "World" was printed.
- If it will take more than 3 seconds, Go function will not be excuted.
Go routines and Sync
- Goroutines shouldn't be overused
- In some cases, like reference counters, old school locking makes more sense
- Go providers the ability to locking via the stnc package