Why use Goroutines instead of Threads
introduce
Both Goroutines and Threads are built for concurrency. Goroutines don’t exactly replace Threads. Because goroutines are actually built on top of a set of Threads. The ability to multipath concurrent execution is multiplexed on the Threads group. When a Goroutine needs to run, it is automatically mounted to a thread. And this series of scheduling is black box to the developer, no perception.
Advantages of Goroutines over Threads
- Overhead is very cheap, requiring only a few kilobytes per Goroutine stack, and can grow and shrink as the application needs.
- A thread can have multiple goroutines, and perhaps thousands of goroutines can be processed by a single thread. If there are goroutines in the thread that need to be suspended, waiting for user input, the other goroutines that need to be run are moved to a new thread. All of these are abstracted and can be used by developers with simple apis.
Using goroutine
package main
import (
"fmt"
"time"
)
func hello() {
fmt.Println("hello goroutine\r")
}
func main() {
go hello()
time.Sleep(1 * time.Second)
fmt.Println("main function\r")}Copy the code
Sleep(1 * time.second). Because:
- When a goroutine is created, it immediately returns, executes the statement, and fools all the return values of the Goroutine.
- If the main goroutine exits, no other Goroutine will be executed;
- If you comment out the sentence Sleep, run it again and you won’t see the Hello Goroutine output.
More than one goroutine
package main
import (
"fmt"
"time"
)
func numbers() {
for i := 1; i <= 5; i++ {
time.Sleep(500 * time.Millisecond)
fmt.Printf("%d ", i)
}
}
func alphabets() {
for i := 'a'; i <= 'c'; i++ {
time.Sleep(1000 * time.Millisecond)
fmt.Printf("%c ", i)
}
}
func main() {
go numbers()
go alphabets()
time.Sleep(3000 * time.Millisecond)
fmt.Println("main terminated")}Copy the code
The output is:
a 1 b 2 c 3 d 4 e 5 main terminated
Copy the code
The table below describes the timing of the execution of multiple Goroutines. You can see that multiple Goroutines are executed simultaneously.
- numbers goroutine
0ms | 500ms | 1000ms | 1500ms | 2000ms | 2500ms |
---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 |
- alphabets goroutine
0ms | 400ms | 800ms | 1200ms | 1600ms | 2000ms |
---|---|---|---|---|---|
a | b | c | d | e |
- main goroutine
0ms | 400ms | 500ms | 800ms | 1000ms | 1200ms | 1500ms | 1600ms | 2000ms | 2500ms | 3000ms |
---|---|---|---|---|---|---|---|---|---|---|
a | 1 | b | 2 | c | 3 | d | 4(e) | 5 |
reference
Part 21: Goroutines
For more content, follow me on Github.