- 进程:太重
- 线程:上下文切换开销太大
- 协程:轻量级的线程,简洁的并发模式
Golang协程:goroutine
package main import "fmt" func main() { fmt.Println("Hello world!") }
- go发起一个协程
- channel协程间通信,通道
- buffered channels具备缓冲队列的通道
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!") }
原文:https://www.cnblogs.com/wozixiaoyao/p/11844949.html