douchixu3686 2017-02-28 19:00
浏览 42

如何停止goroutine [重复]

This question already has an answer here:

I have a goroutine that calls a function and with a special parameter i want to start or stop this goroutine. My problem is that this code never stops my goroutine, it creates everytime a new job.

quit := make(chan bool)
run := make(chan bool)

    go func() {
        for {
            select {
            case <-quit:
                close(run)
            case <-run:
                myFunc(c)
            default:
            }
        }
    }()

    if x == true {
        quit <- true
    } else {
        run <- true
    }

How do I stop my routine?

</div>
  • 写回答

3条回答 默认 最新

  • doudi1449 2017-02-28 19:08
    关注

    When you close the run channel, case <-run will always trigger: listening on a closed channel returns a zero value immediately.

    if you want to stop the goroutine, you should return after you get the <-quit signal.

    As a side note, your default: clause makes the for loop actively work, you should get rid of it (you will still be listening on both channels)

    评论

报告相同问题?