douji1058 2018-11-29 21:08
浏览 66

如何通过调用struct方法来启动/停止功能

Please see the following example.

Playground link

type runner struct{}

func (r *runner) StopProcessing() {
    // how to stop?
}

func (r *runner) StartProcessing() {

    go func() {
        for {
            fmt.Println("doing stuff")
            time.Sleep(1 * time.Second)
        }
    }()

}

As you can see I have a struct which does stuff, it's "running". It starts running when I call the run.StartProcessing() method. It then fires an endless running for{}-loop in a goroutine. Great, but I also want to be able to stop this process. And I really don't know how to achieve this. Any help is highly appreciated.

  • 写回答

3条回答 默认 最新

  • duansengcha9114 2018-11-29 21:18
    关注

    By using a channel to signal when to break out of a goroutine. The relevant part of your code would look something like this

    type runner struct {
        stop chan bool
    }
    
    func (r *runner) StopProcessing() {
        r.stop <- true
    }
    
    func (r *runner) StartProcessing() {
        r.stop = make(chan bool)
        go func() {
            for {
                fmt.Println("doing stuff")
                time.Sleep(1 * time.Second)
                select {
                case _ = <-r.stop:
                    close(r.stop)
                    return
                default:
                }
            }
        }()
    }
    

    You can see a full example here https://play.golang.org/p/OUn18Cprs0I

    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了