我们知道go语言内置的channel缓冲大小是有上限的,那么我们自己如何实现一个无限缓冲的通道呢?
代码如下:
package main
import (
"container/list"
"fmt"
"sync"
)
func UnlimitedChannel() (chan <- interface{},<- chan interface{}) {
send := make(chan interface{},1)
receive := make(chan interface{},1)
go createQueue(send,receive)
return send,receive
}
func createQueue(send <- chan interface{},receive chan <- interface{}) {
queue := list.New()
for {
if front := queue.Front();front == nil{//队列为空,即队首无值
if send == nil{
close(receive)
return
}
data ,ok := <-send
if !ok{
close(receive)
return
}
queue.PushBack(data)
}else {//队列不为空,即队首有值
select {
case receive <- front.Valu