golang的缓冲channel简单使用

栏目: Go · 发布时间: 5年前

内容简介:我们常用的是无缓冲channel :其实make() 创建chan的第二个参数可设置缓冲channel的大小。 上述语句等价于 make(chan type, 1) 即创建了一个缓冲区大小为1channel下面看有缓冲channel的两个例子.

我们常用的是无缓冲channel :

make(chan type)

其实make() 创建chan的第二个参数可设置缓冲channel的大小。 上述语句等价于 make(chan type, 1) 即创建了一个缓冲区大小为1channel

下面看有缓冲channel的两个例子.

阻塞型

demo : 协程1 :每隔1s 往有10个缓冲的channel里面写一条msg,

协程2:每隔3s 取一条msg,

package main 

import(
	//"fmt"
	"time"
	"strconv"
	log "github.com/astaxie/beego/logs"
)

func main() {
	log.Debug("---main--- start")

	msgs := make(chan string, 10)

	i := 0

	go func() {
		time.Sleep(3*time.Second)

		for {
			time.Sleep(1*time.Second)
			i++
			msg := "msg " + strconv.Itoa(i)
			msgs <- msg
			log.Debug("------ put msg : ", msg)
		}
	}()

	go func() {

		for {

			get := <- msgs

			log.Debug("---------------- pop msg : ", get)

			time.Sleep(3*time.Second)
		}

	}()

	time.Sleep(100*time.Second)

}

可以看到当缓冲区满了以后,写channel的操作会阻塞在那里等待读端取走msg后才能写入。

golang的缓冲channel简单使用

非阻塞

实际场景中我们可能不希望程序阻塞,那么可以使用select来控制,当缓冲区满了后忽略该条msg继续执行我们的程序。

package main 

import(
	//"fmt"
	"time"
	"strconv"
	log "github.com/astaxie/beego/logs"
)

func main() {
	log.Debug("---main--- start")

	msgs := make(chan string, 3)

	i := 0

	go func() {
		time.Sleep(3*time.Second)

		for {

			time.Sleep(1*time.Second)
			i++
			msg := "msg " + strconv.Itoa(i)

			select {
				case msgs <- msg:
					log.Debug("------ put msg : ", msg)
				default :
					log.Debug("-----msgs chan cache full sleep 1s-----")
					log.Debug("-----ignore this msg-----> : ", msg)
			}
		}
	}()

	go func() {

		for {

			get := <- msgs

			log.Debug("---------------- pop msg : ", get)

			time.Sleep(3*time.Second)
		}

	}()

	time.Sleep(100*time.Second)

}

可以看到,因为写端写入过快,再写入msg6时缓冲区已满,执行default丢弃了msg6,读端在取走msg5后, 取走的不是msg6,而是msg7

golang的缓冲channel简单使用


以上所述就是小编给大家介绍的《golang的缓冲channel简单使用》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Introduction to Computation and Programming Using Python

Introduction to Computation and Programming Using Python

John V. Guttag / The MIT Press / 2013-7 / USD 25.00

This book introduces students with little or no prior programming experience to the art of computational problem solving using Python and various Python libraries, including PyLab. It provides student......一起来看看 《Introduction to Computation and Programming Using Python》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具