Created
April 29, 2019 10:06
-
-
Save polebug/8d9cfc4942101c32392dfdb30e555789 to your computer and use it in GitHub Desktop.
Go 中 channel 的使用
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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