Shutting down goroutines gracefully

% whoami

bia

Sr. Software Engineer @ RedHat

 

previously...

SRE Tech Lead/Manager @ Stone

  1. Having fun with goroutines

  2. Finishing work properly

  3. Listening to system signals

  4. Handling interrupts in a production environment

Agenda

Let's say hello first!

What on earth are goroutines?

Goroutines are lightweight threads that are managed by the Go Runtime.

 

The main function is a goroutine itself and it can launch other goroutines that run concurrently to it.

Let's spawn some goroutines!

But why is my program closing without the goroutines finishing their work?

Program execution

(...)

Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete.

  1. Having fun with goroutines

  2. Finishing work properly

  3. Listening to system signals

  4. Handling interrupts in a production environment

Agenda

If we want to wait until the goroutine is done, we need to tell the main program to wait.

This can be achieved with a synchronization technique, and Go's sync package provides us something called WaitGroup

Let's give it a Go!

But have if I have to exit earlier? Can I act on this interruption?

Yes.

 

By listening to system signals.

  1. Having fun with goroutines

  2. Finishing work properly

  3. Listening to system signals

  4. Handling interrupts in a production environment

Agenda

We can start listening to system signals to handle the execution of our program

By system signals, I mean actual, POSIX signals

SIGINT

SIGTERM

SIGKILL

 

SIGSTOP -> SIGCONT

... and we can listen to a signal by using Go's notify function and passing a channel to it

If you're wondering what a Go channel is...

"A channel provides a mechanism for concurrently executing functions to communicate by sending and receiving values of a specified element type."

... so when your program receives that signal, you will receive a value in that channel

... communicating by channel is very common amongst goroutines and is the right away to pass values from one goroutine to another

Let's do this then!

Now, everytime a interrupt happens, we can listen to it and do a subsequent action

We can either wait for the tasks to be done, or introduce a new status

  1. Having fun with goroutines

  2. Listening to system signals

  3. Finishing work properly

  4. Handling interrupts in a production environment

Agenda

If we send this code containerized to run inside of a K8S cluster, what happens?

That'd be all!

 

You can find me on twitter (@__biancarosa) if you wanna chat!

 

 

Thank you for your time!

Shutting down goroutines gracefully

By Bianca Rosa

Shutting down goroutines gracefully

  • 211