如何在不更改通道内容的情况下打印通道的内容

huangapple go评论69阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年6月4日 22:59:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/30647393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定