Concepts from Communicating Sequential Processes (CSP), channels and select statements, add value as well
- M:N scheduler, which means it maps M green threads to N OS threads.
When we have more goroutines than green threads available, Go's runtime distributes the goroutines to new OS thread
- Goroutine is like Thread, but more effiecient thanks to Go's Runtime
- Many goroutine can be multiplexed on fewer OS's threads m:n where m = Goroutines ; n = threads
- TLDR: 1 Goroutine combines concurrency and parallel by Go's runtime, so 1 Goroutine may NOT = 1 Thread, but behave like it.
In Go,we would create a goroutine for each incoming connection, and then return from the goroutine’s function
A goroutine is a function that is running concurrently
- Fork: split child branch from parent
- Join: Merge child branch with parent
Example
sayHello := func() {
fmt.Println("hello")
}
go sayHello()
- Problem:
main()
will be executed finished beforesayHello()
can run
- Solution:
- Method 1: Add a time.sleep() after
go sayHello()
, but it doesn't create join point, only race condition? - Method 2: Create a join point by synchronize the main goroutine and
sayHello()
goroutine usingsync.WaitGroup
- Method 1: Add a time.sleep() after
var wg sync.WaitGroup
for _, salutation := range[]string{"hello", "greetings", "good day"} {
wg.Add(1)
go func(salutation string) {
defer wg.Done()
fmt.Println(salutation)
}(salutation)
}
wg.Wait()
- We pass the parameter to the closure, a copy of string is made ensure goroutine refers to correct string
- Output
good day
hello
greetings
Page 44-46
- Primative (Wait Group) Page 47-48
- Use for synchronization, allow 1 goroutine to wait for group of other goroutine to complete tasks.
- Channel (Page 64-78)
- for communication btw goroutine, allow goroutine send and receive data, acts as Pipeline
- What is
Pipeline
(Page 100-113)
- When to use Wait Group or Channel?
- Wait Group
- Channel:
- Errors & Warnings:
Page 49-52
Page 52-57
Page 58-59
Page 59-64
Page 78-82
Page 85-88
Page 89-90
Page 90-94
Page 94-96
Page 97-100
Page 114-119
Page 119-120
Page 120-121
Page 121-123
Page 124-130
Page 131-145