生命不止,继续 go go go !!!
golang就是为高并发而生的,为我们提供了goroutines和channel。虽然前面博客的代码片段中也有用到这两个关键字,但是一直没有组织好语言,也没有能力把goroutines和channel写好,那么估计我们先用,然后再看看的理解。
goroutines
A goroutine is a lightweight thread managed by the Go runtime.
几个关键字:轻量级,线程。
package mainimport ( "fmt" "time")func say(s string) { for i := 0; i < 5; i++ { time.Sleep(100 * time.Millisecond) fmt.Println(s) }}func main() { go say("world") say("hello")}
区别:
f() // call f(); wait for it to return go f() // create a new goroutine that calls f(); don't wait12
channels
Channels are the pipes that connect concurrent goroutines.
几个关键字:管道 连接。
package mainimport