How to create threads in Golang

ยท

3 min read

Table of contents

No heading

No headings in the article.

Golang was designed by Robert Griesemer, Rob Pike, and Ken Thompson. Commonly, known as Go, this language is popular for its very effective concurrency model. Creating and maintaining a large number of threads can take much of the computer resources which might not be efficient enough. Go tackles this issue by using goroutines and channels. You can think of goroutine as a new thread (this is just to understand, ideally multiple goroutines live on a single thread that lives on a single process). We can have thousands of goroutines running on a system which is not possible with threads.

Now, how can we create a goroutine in Golang. For that, we use the keyword go. Let's understand this with code. The below code is a normal one without a goroutine and this will help us in understanding the difference that goroutine brings with it.

func newThread(thread_name string) {
    for i := 0; i < 5; i++ {
    print(thread_name, "\n")
        time.Sleep(1 * time.Second) // Sleep for 1 second
    }
}

func main() {
    newThread("Another thread")
    newThread("Main thread")
}

Here we see a function newThread which will take thread_name as input and print it 5 times in for loop. I have used Sleep() method to show what is actually being printed out at each stage. So, after printing one line, the program will sleep for 1 second and then again print the thread_name. What is the expected output here?

Another thread
Another thread
Another thread
Another thread
Another thread
Main thread
Main thread
Main thread
Main thread
Main thread

This was fairly easy to guess as it behaves like a normal program. Now let's change one line in this code to create a goroutine (In the code I am writing thread instead of goroutine so that goroutine doesn't become confusing for you, but essentially by saying create a new thread, I basically mean create a new goroutine). Also, a very important point is that the main function is the default goroutine in Golang. So, even if we have no goroutines defined in the program, it will still have one goroutine that will execute the main function. So, in the above code, we were actually running one goroutine but it was running by default so we don't care about that.

func newThread(thread_name string) {
    for i := 0; i < 5; i++ {
        print(thread_name, "\n")
        time.Sleep(1 * time.Second) // Sleep for 1 second
    }
}

func main() {
    go newThread("Another thread") //Added go keyword here
    newThread("Main thread")
}

Now can you guess its output ?? It will print this :

Main thread
Another thread
Another thread
Main thread
Main thread
Another thread
Another thread
Main thread
Main thread
Another thread

This sequence of results in output can change each time you run the program, the sequence can be random at each execution. But the essence here is that by adjoining the function call with the go keyword, user is telling program to create another goroutine or for simplicity let's say another thread that will execute parallelly with the main thread. That is why we see both threads being printed here in parallel. This diagram can help you better understand what is happening when we run the code. (Black boxes are the actual code lines being executed and orange boxes are the description of what is happening after each line execution)

diag.png

๐Ÿ‘‰ What can you learn next: channels. These are essential for effectively using goroutines in Golang. channel helps in transporting data from one goroutine to another one.

ย