英文:
How to print contents of channel without changing it
问题
我正在使用Go语言编写一个程序,遇到了一个简单的问题:
我在程序中使用了一些goroutine和通道来进行通信。我想要定期检查通道中的内容,但又不想中断goroutine的工作。通道是否有任何函数可以打印它们的内容?或者我应该如何复制它们?
var shelf chan int = make(chan int, 5)
go Depot(shelf)
go Shop(shelf)
var input string
fmt.Scanln(&input)
if input == "print" {
// 在这里打印shelf上的内容
}
请注意,我只会翻译代码部分,不会回答关于翻译的问题。
英文:
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
得分: 6
如何在不中断goroutine的工作的情况下实现这一点?
简单的答案是,你不能在不中断的情况下实现这一点。通道是一种同步原语,意味着它们使并发程序能够安全地进行通信。如果你从通道中取出某个元素,这个“取出”操作是原子性的,其他人无法从同一个通道中取出相同的元素。这是有意为之的。
你可以在打印完元素后将其放回通道。这种方法的问题是,某些元素可能永远不会被打印,而其他元素可能会被打印多次,因为所有涉及的goroutine都在竞争从通道中获取元素。
听起来你可能需要的不仅仅是一个通道。
英文:
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论