本文介绍了如果在第一次迭代和第二次迭代之间存在小的时刻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在下面的代码中,迭代运行两次。 是否有可能在第一次迭代和第二次迭代之间运行test2< - true?我的意思是,当第一次迭代结束并且第二次迭代没有开始时,是否发生了改变,使其发送到test2? package main importlog importtime func main(){ test:= make(chan bool,1) test2:= make(chan bool,1) $ b $ fun func(){ for { select { case< -test: log.Println(test) case< -test2: log.Println(test2)} test< - true time.Sleep(1) test2< - true time.Sleep 1)} 解决方案是的。由于你的频道是缓冲的,可以保存1个值。主执行流程可以在没有匿名goroutine读取您发送给 test 通道的值的情况下继续执行,并且可以在 test2 channel在goroutine醒来之前读取 test 频道上的值。 这是不太可能发生,因为你有一段时间。睡眠()通常给那里的时间让goroutine执行,但是不知道在你的机器很忙的情况下会发生什么,在(如果你的 test 频道是无缓冲的,那么 test< - true 语句将会阻塞,直到你的goroutine收到该值为止,并且至少不可能从 test2 ,然后从测试频道收到任何内容。 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 mainimport "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)} 解决方案 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. 这篇关于如果在第一次迭代和第二次迭代之间存在小的时刻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-30 00:27
查看更多