duanci3845 2014-07-26 18:00
浏览 100
已采纳

如果在第一次迭代和第二次迭代之间有一小段时间

In the code below, iterations are runned two times.
Is it possible that "test2 <- true" is runned at the moment which is just between the first iteration and the second iteration?
I mean, is there a change to send true to "test2" when the first iteration is ended and the second iteration is not started?

package main

import "log"
import "time"

func main() {
    test := make(chan bool, 1)
    test2 := make(chan bool, 1)

    go func() {
        for {
            select {
            case <-test:
                log.Println("test")
            case <-test2:
                log.Println("test2")
            }
        }
    }()

    test <- true
    time.Sleep(1)
    test2 <- true
    time.Sleep(1)
}
  • 写回答

2条回答 默认 最新

  • douhan4093 2014-07-26 18:21
    关注

    Yes. Since your channels are buffered and can hold 1 value. the main execution flow can continue without your anonymous goroutine reading the value you send to the test channel, and it can send a value on the test2 channel before the goroutine wakes up and read the value on the test channel.

    This is unlikely to happen, since you have a time.Sleep() call there to normally give time for the goroutine to execute, but there's no telling what'll happen in a corner case of your machine being very busy, being power suspended at an (un)lucky time or other things you didn't think about.

    If your test channel was unbuffered, the test <- true statement would block until your goroutine received the value, and there would at least be no possibility for the goroutine to receive from test2 before receiving anything from the test channel.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#开发语言#的问题:FDTD建模问题图中代码没有报错,但是模型却变透明了
  • ¥15 uniapp的h5项目写一个抽奖动画
  • ¥15 TeleScan不能修改bar
  • ¥100 请问我基于逐飞库写的这个有关于mp u6050传感器的函数,为什么输出的值是固定的?
  • ¥15 hadoop中启动hive报错如下怎么解决
  • ¥15 如何优化QWebEngineView 加载url的速度
  • ¥15 关于#hadoop#的问题,请各位专家解答!
  • ¥15 如何批量抓取网站信息
  • ¥15 Spring Boot离线人脸识别
  • ¥15 使用Ant Design Pro vue的时候,使用环境变量的时候,构建报错是什么原因