Golang协程实现流量统计系统(3)
进程、线程、协程
- 进程:太重
- 线程:上下文切换开销太大
- 协程:轻量级的线程,简洁的并发模式
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!") }
作者: 元宝爸爸
出处:https://www.cnblogs.com/wozixiaoyao/p/11965398.html
版权:本文采用「署名-非商业性使用-相同方式共享 4.0 国际」知识共享许可协议进行许可。
觉得文章不错,点个关注呗!