Go并发缓冲channel

无缓存

ch := make (chan int) 等价于 ch := make (chan int, 0)

无缓存的channel,如果想要写入值,但没有人读的话,写的值会一直写不进去(阻塞在写入处)。直到有人读取,才会写入,并传递到读出的数那里。

package main

import (
	"fmt"
	"time"
)

var ch chan int

// 写chan
func writech(){
	ch <- 1
	fmt.Println("writech end")
}

func main(){
	ch = make (chan int, 0)

	go writech()
	time.Sleep(2 * time.Second)

	// 读chan
	fmt.Println("start to read chan")
	<-ch

	time.Sleep(time.Second)
	fmt.Println("end main")
}

有缓存

缓冲满了之后阻塞,除非有人对它操作(读)

package main

import (
	"fmt"
	"time"
)

var ch chan int

// 写chan
func writech(){
	ch <- 1
	fmt.Println("writech 1")
	ch <- 2
	fmt.Println("writech 2")
	ch <- 3
	fmt.Println("writech 3, end")
}

func main(){
	ch = make (chan int, 2)

	go writech()
	time.Sleep(2 * time.Second)

	// 读chan
	fmt.Println("start to read chan")
	<-ch
	fmt.Println("chan read end")

	time.Sleep(time.Second)
	fmt.Println("end main")
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值