Skip to content

Instantly share code, notes, and snippets.

@polebug
Created April 29, 2019 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polebug/8d9cfc4942101c32392dfdb30e555789 to your computer and use it in GitHub Desktop.
Save polebug/8d9cfc4942101c32392dfdb30e555789 to your computer and use it in GitHub Desktop.
Go 中 channel 的使用
package main
import (
"fmt"
"time"
)
// 使用 make 建立一个 channel
// 定义只能接受的 channel
// var receive_only chan int = make(<-chan int)
// 定义只能发送的 channel
// var send_only chan int = make(chan<- int)
// 定义可同时发送接受的 channel
var send_receive chan int = make(chan int)
func send(channel chan<- int) {
for i := 0; i < 10; i++ {
fmt.Println("send ready: ", i)
channel <- i
fmt.Println("has send: ", i)
}
}
func recv(channel <-chan int) {
for i := range channel {
fmt.Println("has received: ", i)
}
}
func main() {
go send(send_receive)
go recv(send_receive)
time.Sleep(3 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment