Golang控制goroutine的启动与关闭

  最近在用golang作项目的时候,使用到了goroutine。在golang中启动协程很是方便,只须要加一个go关键字:java

   

 go myfunc(){

      //do something }()

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

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

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

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

 

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))
}
相关文章
相关标签/搜索