旃麒雅 发表于 2018-9-20 07:13:57

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))
  
}
  

  



页: [1]
查看完整版本: Golang控制goroutine的启动与关闭