如何在不等待的情况下从通道中获取值

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

How to get a value from a channel without waiting for it

问题

在Go语言中,如果我尝试从一个通道接收数据,程序的执行将会停止,直到通道中有值为止。然而,我想要做的是让程序继续执行,并且如果通道中有值,对其进行操作。

我心中的伪代码大致如下:

mychan := make(chan int, 1)

go someGoRoutine(mychan) // 这可能会在某个时刻向mychan中放入一些值

for {
	if "mychan"中有值 {
		// 从"mychan"中移除元素并进行处理
	} else {
		// 其他代码
	}
}

据我了解,我不能简单地使用v <- mychan,因为这会阻塞程序的执行,直到有值可用。在Go语言中,应该如何实现这个功能呢?

英文:

In Go, if I try to receive from a channel, the program's execution is going to be stopped until some value is in the channel. However, what I would like to do is let the program execution continue and, if there's a value in the channel, act on it.

The pseudo-code I have in mind is something like this:

mychan := make(chan int, 1)

go someGoRoutine(mychan) // This might put some value in mychan at some point

for {
	if something in &quot;mychan&quot; {
		// Remove the element from &quot;mychan&quot; and process it
	} else {
		// Other code
	}
}

As I understand, I cannot simply use v &lt;- mychan because that would block the program execution until a value is available. What would be the way to do this in Go?

答案1

得分: 8

那就是 select 的作用。例如:

for {
        select {
        case v := &lt;-c1:
                // 处理 v
        case v, ok := &lt;-c2:
                // 第二种形式,'!ok' -> c2 已关闭
        default:
                // 接收未完成
        }
}
英文:

That's what select is for. For example:

for {
        select {
        case v := &lt;-c1:
                // process v
        case v, ok := &lt;-c2:
                // Second form, &#39;!ok&#39; -&gt; c2 was closed
        default:
                // receiving was not done
        }
}

huangapple
  • 本文由 发表于 2013年7月16日 15:42:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/17670787.html
匿名

发表评论

匿名网友

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

确定