進程、線程、協程
- 進程:太重
- 線程:上下文切換開銷太大
- 協程:輕量級的線程,簡潔的併發模式
Golang協程:goroutine
Hello world
package main import "fmt" func main() { fmt.Println("Hello world!") }
Golang協程特性實踐
- go發起一個協程
- channel協程間通信,通道
- buffered channels具備緩衝隊列的通道
go協程和channel初次使用
package main import ( "fmt" ) func main() { message := make(chan string)//定義一個string型的channel go func() { message <- "hello goroutine!" }() fmt.Println( <- message ) fmt.Println("Hello world!") }
多個協程
package main import ( "fmt" "time" ) func main() { message := make(chan string) //定義一個string型的channel go func() { message <- "hello goroutine!" }() go func() { time.Sleep(2 * time.Second) str := <-message str = str + "I'm goroutine!" message <- str }() time.Sleep(3 * time.Second) fmt.Println(<-message) fmt.Println("Hello world!") }