Goroutines: Threading made easy!

This post is dedicated to the awesome concept of “Goroutines” in Go. A “Goroutine” (Go Routine?) is a lightweight thread implementation that executes asynchronously with the main process. To define a goroutine, we use the “go” keyword before a function call. Instead of a regular blocking call, the function is then executed asynchronously.

Let’s jump into a quick demonstration. We shall write a program that creates multiple threads, each thread sleeping for a random period of time. For us, the mere mortals, we shall politely ask the threads to print some information so that we can tell when they go to sleep and when they wake up!

The blocking call (from the main process) always executes first. The Scanln() call waits for user input thus allowing the async functions to print their information on the terminal. If we don’t wait, the main process will finish execution and the program will quit. Since the other functions are async, we shall never see their outputs. So we wait and wait for their messages! 🙂

Sample output?

It’s simple, right? In some languages, you have to subclass a built in class and then define specific methods to direct the behavior/actions. In Go, you just define a function and prepend “go” before making the function call. Good thing, you can use anonymous functions and invoke them immediately as well.

For communication between these goroutines, we can use “Channels”. Hope to write another blog post on using channels soon.

2 Comments Goroutines: Threading made easy!

Leave a Reply
