将缓冲通道写入超过其容量的内容。

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

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 &quot;fmt&quot;
    
    func main() {
    	ch := make(chan int, 2)
    	go func (){
    	ch &lt;- 1
    	ch &lt;- 2
    	ch &lt;- 4//blocks here but scheduler picked up another go routine
    	ch &lt;- 6
        ch &lt;- 10
        //close(ch)
    	}()
    	fmt.Println(&lt;-ch)
    	fmt.Println(&lt;-ch)
        //for v:=range ch{
        //fmt.Println(&lt;-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(&lt;-ch).

Even if the anonymous goroutine is blocked on ch &lt;- 4, the all program stops anyway.

huangapple
  • 本文由 发表于 2021年10月3日 03:38:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/69419668.html
匿名

发表评论

匿名网友

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

确定