golang chan

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/youshijian99/article/details/84960404


 

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

猜你喜欢

转载自blog.csdn.net/youshijian99/article/details/84960404