dongzhanlu0658 2018-02-28 04:59
浏览 6
已采纳

通道结束父例程后返回

I have a code excerpt of a main running a go routine below. Why does this NOT happen: the main exits after it receives the done and before job return, which would make the child process zombie. Any reference to golang docs would be helpful.

func main() {
    var jobDone = make(chan bool)
    go job(jobDone)
    <-jobDone
}

func job(done chan bool) {
    for {
        select {
        case <-someOtherGlobalChannel:
            //Please ignore this case/channel
            fmt.Println("SOmeOtherChannel received")
        default:
            if check_somthing_expression {
                done <- true
                return
            }
        }
    }
}
  • 写回答

3条回答 默认 最新

  • dsqbh42082 2018-02-28 15:08
    关注

    Zombie Process

    "...which would make the child process zombie"

    go job() does not start a separate process, it starts another goroutine. You have a main goroutine, and a job goroutine in this program. Language spec:

    A "go" statement starts the execution of a function call as an independent concurrent thread of control, or goroutine, within the same address space.

    Therefore you will not be creating a Unix zombie process.

    Main Not Exiting Before Job

    "Why does this NOT happen: the main exits after it receives the done and before job return...?"

    Reason #1: The Receive Operations are Blocking Both Goroutines

    (1) Because there's no send statement on channel done in job.

    <-done
    

    is a receive operation. See "Receive operator" in Go spec:

    For an operand ch of channel type, the value of the receive operation <-ch is the value received from the channel ch.

    See also "Send statements" in Go spec:

    ch <- 3 // send value 3 to channel ch

    You need a send statement. E.g.:

    done <- true
    

    More explanatory text and examples are available in the Go Tour and Effective Go.

    ...And there's a second reason:

    Reason #2: There's Nothing To Do Between Send and Return

    (2) Because, even if you change the receive operation to a send statement, there's nothing to do in the job goroutine between when it sends on the channel and it returns, so it's not likely for any time to pass from one to the next. If you want that to happen, add a sleep in job using the time package:

    done <- true
    time.Sleep(time.Second * 30)
    return
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100