赞
踩
- package main
-
- import "fmt"
-
- func main() {
- c := make(chan int, 1)
- select {
- case c <- 10 : // 写入chan
- }
-
- select {
- case c <- 20 : // 写入chan,写不进去就丢弃
- default:
- }
-
- value , ok := <- c // 从chan中读取,ok是用来判断通道c是否关闭,
- // 如果通道c关闭,仍然有数据,则ok为true,直到没有数据ok为false
- fmt.Printf("value(%T)(%v) = %v\n",value, ok, value)
- close(c)
- value , ok = <- c // 从chan中读取
- fmt.Printf("value(%T)(%v) = %v\n",value, ok, value)
-
- }
value(int)(true) = 10
value(int)(false) = 0
带缓存chan
- package main
- import (
- "fmt"
- "time"
- )
- func send(p chan<- int) {
- for i := 0; i < 5; i++ {
- p <- i
- fmt.Println("send:", i)
- }
- }
-
- func receive(c <-chan int) {
- for i := 0; i < 5; i++ {
- v := <-c
- fmt.Println("receive:", v)
- }
- }
-
- func main() {
- ch := make(chan int,5)
- go send(ch)
- go receive(ch)
- time.Sleep(1 * time.Second)
- }
send: 0
send: 1
send: 2
send: 3
send: 4
receive: 0
receive: 1
receive: 2
receive: 3
receive: 4
不带缓存chan
- package main
- import (
- "fmt"
- "time"
- )
- func send(p chan<- int) {
- for i := 0; i < 5; i++ {
- p <- i
- fmt.Println("send:", i)
- }
- }
-
- func receive(c <-chan int) {
- for i := 0; i < 5; i++ {
- v := <-c
- fmt.Println("receive:", v)
- }
- }
-
- func main() {
- ch := make(chan int)
- go send(ch)
- go receive(ch)
- time.Sleep(1 * time.Second)
- }
receive: 0
send: 0
send: 1
receive: 1
receive: 2
send: 2
send: 3
receive: 3
receive: 4
send: 4
- package main
- import (
- "fmt"
- "time"
- )
- func send(p chan<- int) {
- for i := 0; i < 3; i++ {
- p <- i
- fmt.Println("send:", i)
- }
- }
-
- func receive(p <- chan int){
- for{
- select{
- case <-p:
- fmt.Println("hello world")
- }
- }
-
- }
-
- func main() {
- ch := make(chan int)
- go send(ch)
- go receive(ch)
- time.Sleep(1 * time.Second)
- }
send: 0
hello world
hello world
send: 1
send: 2
hello world
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。