爲何要使用 goroutines 取代 threadsgit
goroutines 和 threads 都是爲了併發而生。準確的說,並不能說 goroutines 取代 threads。由於其實 goroutines 是創建在一組 threads 之上。將多路併發執行的能力複用在 threads 組上。當某一個 goroutine 須要運行時,會自動將它掛載到一個 thread 上。並且這一系列的調度對開發者是黑盒,無感知的。github
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")
}
複製代碼
細心的同窗必定會問到爲何須要執行 time.Sleep(1 * time.Second) 這句話。由於:golang
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")
}
複製代碼
輸出爲:bash
a 1 b 2 c 3 d 4 e 5 main terminated
複製代碼
下面表格描述多個 goroutine 執行的時序,能夠看出多個 goroutine 是同時進行的。併發
0ms | 500ms | 1000ms | 1500ms | 2000ms | 2500ms |
---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 |
0ms | 400ms | 800ms | 1200ms | 1600ms | 2000ms |
---|---|---|---|---|---|
a | b | c | d | e |
0ms | 400ms | 500ms | 800ms | 1000ms | 1200ms | 1500ms | 1600ms | 2000ms | 2500ms | 3000ms |
---|---|---|---|---|---|---|---|---|---|---|
a | 1 | b | 2 | c | 3 | d | 4(e) | 5 |
更多內容,歡迎關注個人Github。線程