英文:
writing to buffer channel more than its capacity
问题
超过缓冲通道容量的覆盖会有什么影响吗?
由于存在另一个goroutine,并且主goroutine没有与其合并,所以这里不会发生死锁。
package main
import "fmt"
func main() {
ch := make(chan int, 2)
go func() {
ch <- 1
ch <- 2
ch <- 4 // 在这里阻塞,但调度器选择了另一个goroutine
ch <- 6
ch <- 10
//close(ch)
}()
fmt.Println(<-ch)
fmt.Println(<-ch)
//for v := range ch {
//fmt.Println(<-ch)//1 2 4 6 10
//}
}
请注意,这只是代码的翻译部分,不包括任何其他回答。
英文:
overwriting the buffer channel more than its capacity does have any effects ?<p>
Since there is another go routine and main go routine doesn't join with it so no deadlock here
package main
import "fmt"
func main() {
ch := make(chan int, 2)
go func (){
ch <- 1
ch <- 2
ch <- 4//blocks here but scheduler picked up another go routine
ch <- 6
ch <- 10
//close(ch)
}()
fmt.Println(<-ch)
fmt.Println(<-ch)
//for v:=range ch{
//fmt.Println(<-ch)//1 2 4 6 10
//}
}
答案1
得分: 0
因此,这里没有死锁的原因是主函数在第二个fmt.Println(<-ch)
之后退出。即使匿名goroutine在ch <- 4
上被阻塞,整个程序仍然会停止。执行go build -race .
确实可以检测到没有竞态条件。
英文:
> because of that no deadlock here
A go build -race .
would indeed detect no race condition.
But the main reason there is no deadlock, is that the main function exits after the second fmt.Println(<-ch)
.
Even if the anonymous goroutine is blocked on ch <- 4
, the all program stops anyway.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论