Use goroutine like thread

Wen Tao
modern-go
Published in
2 min readMar 2, 2018

Go has a awesome language feature called “goroutine”. However, I miss the old school “thread” api sometime. There are two features missing:

  • cancel and wait the goroutine quit
  • unhandled panic handler

So, here is what I come up, a tiny library https://github.com/modern-go/concurrent:

executor.StopAndWaitForever

It is a very simple library to attach the started goroutine to a executor object. One executor object can be used by manage just one or many goroutines.

You can choose to

  • Stop: the goroutine will quit sometime later
  • StopAndWait: we will wait, until you cancel the wait
  • StopAndWaitForever: will until the goroutine has quit

It is useful to use stop and wait to graceful shutdown my service. But it is annoying to wait without knowing which goroutine is blocking in the way.

when we set InfoLogger, we can see who is blocking

UnboundedExecutor is still waiting goroutines to quit startFrom /home/xiaoju/workspace/src/github.com/modern-go/concurrent/unbounded_executor_test.go:25 count 1
...
goroutine exited
executor stopped

Internally, we are using the function line number to identify the goroutine. And every goroutine life-cycle is tracked, so we know exactly “who” and “how many” is still hanging there.

Another thing we would like to provide is how panic is handled. The default behavior of goroutine is to crash the process. Sometimes, this behavior is desirable. Sometimes, it is not. We would like to make the “default” behavior user defined.

by defining concurrent.HandlePanic, we can control how unhandled goroutine panic will be handled globally. If we want to more fine grained control, we can set HandlePanic in the executor level as well.

Hope you will find it useful, and give me a star: https://github.com/modern-go/concurrent

--

--