zoukankan      html  css  js  c++  java
  • Golang控制goroutine的启动与关闭

      最近在用golang做项目的时候,使用到了goroutine。在golang中启动协程非常方便,只需要加一个go关键字:

       

     go myfunc(){
    
          //do something
     }()

       但是对于一些长时间执行的任务,例如:

     go loopfunc(){
              for{
          //do something repeat
               }
      }()

    在某些情况下,需要退出时候却有些不方便。举个例子,你启动了一个协程,长时间轮询处理一些任务。当某种情况下,需要外部通知,主动结束这个循环。发现,golang并没有像java那样中断或者关闭线程的interrupt,stop方法。于是就想到了channel,通过类似信号的方式来控制goroutine的关闭退出(实际上并不是真的直接关闭goroutine,只是把一些长时间循环的阻塞函数退出,然后让goroutine自己退出),具体思路就是就是对于每个启动的goroutine注册一个channel。为了方便后续使用,我封装了一个简单的库:https://github.com/scottkiss/grtm

    原理比较简单,这里不详细说了,直接看源码就可以了。具体使用示例:

    package main
    
    import (
            "fmt"
            "github.com/scottkiss/grtm"
            "time"
           )
    
    func myfunc() {
        fmt.Println("do something repeat by interval 4 seconds")
        time.Sleep(time.Second * time.Duration(4))
    }
    
    func main() {
            gm := grtm.NewGrManager()
            gm.NewLoopGoroutine("myfunc", myfunc)
            fmt.Println("main function")
            time.Sleep(time.Second * time.Duration(40))
            fmt.Println("stop myfunc goroutine")
            gm.StopLoopGoroutine("myfunc")
            time.Sleep(time.Second * time.Duration(80))
    }
    

      

  • 相关阅读:
    JavaScript继承
    UML建模概述
    UML建模—EA创建Use Case(用例图)
    UML建模—EA创建Class(类图)
    UML建模—EA的使用起步
    软件设计原则之 单一职责
    docker使用教程
    Fiddler工具使用介绍
    理解Python协程:从yield/send到yield from再到async/await
    如何简单地理解Python中的if __name__ == '__main__'
  • 原文地址:https://www.cnblogs.com/vimsk/p/4866586.html
Copyright © 2011-2022 走看看