备注:管道的关闭时,管道中就不可以再写入数据,但是我们还是能读取数据的
用内建函数make创建的管道,如果没有定义管道的大小,默认是不能进行缓存的,也就是说,如果
channel:=make(chan string) 这种方法,如果往里面写入数据时必须要定义一个位置读取数据,否则就会发生阻塞死锁(deadlock),但是如果加上大小
例如 :
make(chan string,1024)默认就开启了1024字节的缓存能力大小,不一定需要一个位置去读取,我们也能够写入数据,但是写入的大小不能超过1024字节,否则会溢出,管道类型好比一个队列,定义队列长度,只有出队,我们才能继续进行入队操作。
以下是代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
//生产一个,转运一个,消费一个的模型 package main import ( "fmt" "strconv" "time" ) func main() { //定义库存管道,消费管道 var storage_chan,consumer_chan=make(chan string,1024),make(chan string,1024) //逻辑生产者生产产品放入库存管道->物流运输->消费消费 go product(storage_chan) go wuliu(storage_chan,consumer_chan) go consumer(consumer_chan) time.Sleep(time.Second*100) } /** 生产函数 */ func product(storage_chan chan string){ for i:=0;i<10 ;i++ { shop_id:="产品编号:"+strconv.Itoa(time.Now().Nanosecond()) storage_chan<-shop_id fmt.Println("产品",shop_id,"入库成功") time.Sleep(time.Second*2) } close(storage_chan) fmt.Println("生产结束") } func wuliu(storage_chan,consumer_chan chan string){ for goods:= range storage_chan { consumer_chan<-goods fmt.Println("物流转运编号为:",goods,"到消费者手中成功") time.Sleep(time.Second*2) } fmt.Println("物流转运已经结束") } func consumer(consumer_chan chan string) { for v:=range consumer_chan { fmt.Println("消费商品",v,"完成") } fmt.Println("商品已经被全部消费") } //全部生产完毕,一次性转运消费的模型 package main import ( "fmt" "strconv" "time" ) func main() { //定义库存管道,消费管道 var storage_chan,consumer_chan=make(chan string,1024),make(chan string,1024) call_me:=make(chan string) //这是调度的关键,后面带1024参数代表缓存能力大小,不加上会阻塞,我们是通过这个阻塞来调度任务的进度的 go product(storage_chan,call_me) go wuliu(storage_chan,consumer_chan,call_me) go consumer(consumer_chan) time.Sleep(time.Second*100) } /** 生产函数 */ func product(storage_chan,call_me chan string){ for i:=0;i<10 ;i++ { shop_id:="产品编号:"+strconv.Itoa(time.Now().Nanosecond()) storage_chan<-shop_id fmt.Println("产品",shop_id,"入库成功") time.Sleep(time.Second*2) } close(storage_chan) fmt.Println("生产结束") call_me<-"我把货全部生产好了" } func wuliu(storage_chan,consumer_chan,call_me chan string){ alert:=<-call_me //如果alert没有收到管道的消息,就会阻塞,一直等到有消息后才会继续往下执行 fmt.Println("接到了电话通知") fmt.Println("通知:",alert) for goods:= range storage_chan { consumer_chan<-goods fmt.Println("物流转运编号为:",goods,"到消费者手中成功") time.Sleep(time.Second*2) } fmt.Println("物流转运已经结束") } func consumer(consumer_chan chan string) { for v:=range consumer_chan { fmt.Println("消费商品",v,"完成") } fmt.Println("商品已经被全部消费") } |
© 著作权归作者所有
文章评论(0)