进程、线程、协程
- 进程:太重
- 线程:上下文切换开销太大
- 协程:轻量级的线程,简洁的并发模式
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!") }