go - 使用选择时转到频道缺少偶数
问题描述
我正在使用这个函数来获取从 0 到 100 的数字。
func addone(c chan int) {
for i:= 0; i <= 100; i++{
c <- i
}
close(c)
}
然后我试图输出它:
func printone(c chan int) {
for {
select {
case <-c:
fmt.Println(<-c)
time.Sleep(time.Millisecond * 50)
default:
fmt.Println("dropped")
}
}
}
功能主要:
func main() {
ch := make(chan int)
go addone(ch)
printone(ch)
}
使用 select 时转到频道缺少偶数,例如它是输出:
下降 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 13 9 85 8 8 99 0 0
2、4、6、8等在哪里?
为什么在关闭通道后它会向通道发送零c
?我认为它会在新数据进入并获得“默认”案例之前等待?
解决方案
这是因为您正在从频道读取两次。
首先尝试将通道数据分配给变量。
这是一个例子: https: //play.golang.org/p/ZdSOPe1Gj13
package main
import "time"
import "fmt"
func main() {
// For our example we'll select across two channels.
c1 := make(chan string)
c2 := make(chan string)
// Each channel will receive a value after some amount
// of time, to simulate e.g. blocking RPC operations
// executing in concurrent goroutines.
go func() {
time.Sleep(1 * time.Second)
c1 <- "one"
}()
go func() {
time.Sleep(2 * time.Second)
c2 <- "two"
}()
// We'll use `select` to await both of these values
// simultaneously, printing each one as it arrives.
for i := 0; i < 2; i++ {
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
}
}
推荐阅读
- azure - 部署到 Azure 应用程序时如何在 docker compose 中包含启动脚本
- python - 如何从 yaml 解析任意布尔逻辑
- python - Python - 一个目录中的嵌套文件在另一个目录中导入嵌套文件
- react-native - ReactNative 中整个应用程序的背景图像
- python-3.x - groupby 与熊猫数据框中的条件
- forms - 使用 Thymeleaf 获取内部对象的验证错误的问题
- java - 如何在 Java 中按下按钮使新的随机图像出现?
- python - 使用 for 循环遍历列表,检查字符是否存在。如果存在,将角色放入同一位置的新列表中
- powershell - 监控 MSMQ 传出队列?
- c++ - C26486 与 string_view