How to print contents of channel without changing it

∥☆過路亽.° 提交于 2021-02-07 08:55:19

问题


I'm writing a program in the Go language, and I have a simple problem:

I have some goroutines in my program and channels with which goroutines use to communicate. From time to time I would like to check what is inside the channels. How could I achieve that without interrupting the goroutines' work? Do channels have any function to print their contents? Or should I somehow copy them?

var shelf chan int = make(chan int, 5)
go Depot(shelf)
go Shop(shelf)
var input string
fmt.Scanln(&input)
if (input == "print") {
     //here print what on shelf
}

回答1:


How could I achieve that without interrupting the goroutines' work?

The simple answer is that you can't, without interrupting. Channels are a synchronization primitive, meaning that they are what enables concurrent programs to communicate safely. If you take something out of a channel, that "taking out" happens atomically, nobody else can take the same item out of the same channel. And that's intended.

What you can do is take items out and put them back after printing them. The problem with this approach is that some elements might never be printed while others may be printed more than once as all goroutines involved race to grab items from the channel.

It sounds like you need something else than a channel.



来源:https://stackoverflow.com/questions/30647393/how-to-print-contents-of-channel-without-changing-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!