dongwei2983 2016-06-03 13:54
浏览 60
已采纳

在for循环死锁中选择

https://play.golang.org/p/FyIUPkwq0R

Why does the following deadlock?

package main

import (
    "fmt"
)
var quit chan bool
var buffer chan string

func main() {
        buffer = make(chan string)
    quit = make(chan bool)
    go func() {
        i:=0
        for {
            select {
            case <- quit:
                fmt.Println("Bye!")
                return
            default:
                fmt.Println(<-buffer)
            }
            i++
            fmt.Println(i)
        }
    }()
    buffer <- "Go!"
    quit <- true        // This line dead locks
    //buffer <- "Hello" // When I do this instead it works?
    //quit <- true      // Also when I don't quit it still exit's?
}
  • 写回答

3条回答 默认 最新

  • doudou20145 2016-06-03 14:07
    关注

    This code isn't guaranteed to work properly. You might get lucky, but apparently you've been getting unlucky. You might get lucky and the following might happen:

    Let's say we have two goroutines, A and B, where A is the goroutine running main and B is the goroutine running the anonymous function. The following might happen:

    • B: Execute select; there's nobody writing on the quit channel, so execute the default case
    • B: Execute <-buffer, so begin blocking, waiting for somebody to write to buffer
    • A: Write "Go!" to buffer
    • B: Receive "Go!" and print it. Continue looping.
    • A: Write true to quit
    • B: Execute select; A is trying to write to quit, so execute that case. Print "Bye!" and return
    • A: Since write has finished, continue and return from main

    However, this isn't guaranteed to happen. In particular, after reading from buffer, B might keep executing, execute the select, and fall into the default case before A has a chance to write to quit. That's what's probably happening, and would look like this:

    • B: Execute select; there's nobody writing on the quit channel, so execute the default case
    • B: Execute <-buffer, so begin blocking, waiting for somebody to write to buffer
    • A: Write "Go!" to buffer
    • B: Receive "Go!" and print it. Continue looping
    • B: Execute select; there's nobody writing on the quit channel, so execute the default case
    • B: Execute <-buffer, so begin blocking, waiting for somebody to write to buffer
    • A: Write true to quit, so begin blocking, waiting for somebody to read from quit

    Now both A and B are blocked, and since there are no other goroutines in the system, no event can ever unblock either of them, so the system is stuck.

    Solution

    One way of fixing this would be to make it so that goroutine B reads from the buffer as one of the select cases instead of inside a select case. This way, the select will simply block until either channel becomes available for an action, and your code will behave as you probably wanted it to:

    select {
        case <-quit:
            fmt.Println("Bye!")
            return
        case str := <-buffer:
            fmt.Println(str)
    }
    

    See it here on the Go Playground.

    Note, however, that since the main goroutine is returning as soon as it writes to the quit channel, and the entire Go program exits as soon as that happens, you may (and probably will) get unlucky and fmt.Println("Bye!") will not execute before the program quits.

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

报告相同问题?

悬赏问题

  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格