Multi threading using goroutines

Almost all modern programming languages have support for multi threading & in almost all of the languages multithreading is fragile, you seem to lose control over your threads who share same memory space.

Sharing same memory serves as a communication tool for threads. So producer produces a “thing”.. keeps it in memory, consumer comes and consumes it from memory. Producer checks memory, memory is empty, it produces the thing again and puts in memory… and it continues. Memory could be a variable or a buffer or whatever.. you get the point.

So memory is the communication tool/medium between the threads here. What if we could let threads communicate directly with each other.

Go got you covered with its slogan

Do not communicate by sharing memory; instead, share memory by communicating.

Before we dive into inter thread communication in go, lets first understand threads in go and how we create them.

Multithreading in Go is achieved using Goroutines. A Goroutine is a function which is executed separately from the main function in its own thread. Its like you spawned a new thread which is executing concurrently. Lets see how things actually work

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func talk() {
	for i := 0; ; i++ {
		fmt.Println("This guy is talking")
		amt := time.Duration(rand.Intn(250))
		time.Sleep(time.Millisecond * amt)
	}
}

func listen() {
	for i := 0; ; i++ {
		fmt.Println("This guy is listening")
		amt := time.Duration(rand.Intn(250))
		time.Sleep(time.Millisecond * amt)
	}
}
func main() {
	go talk()
	go listen()
}

Above we have a function talk() which prints “This guy is talking” in an infinite loop, the function has a sleep call which sends the function/thread to sleep after a random time.

Similarly we have a function listen() which prints “This guy is listening” in an infinite loop with random sleep time.

In the main function we call talk() as

go talk()

This actually creates a Goroutine which spawns a new thread and executes the function in the new thread. Here both talk() and listen() are goroutines, so when one thread is sleeping, we will see that other thread is executing and we will see an output like the one below

This guy is listening
This guy is talking
This guy is talking
This guy is talking
This guy is listening
This guy is listening
This guy is talking
This guy is listening
This guy is listening
This guy is talking

Your exact output will differ ofcourse and this will continue indefinitely until you kill the program.

Here we saw how we can create multiple threads from main thread

Next we will see how we can do inter thread communication between these two threads.

Later!

~~ Whizdumb ~~

~~ Whizdumb ~~
Email : sachin.xpert@gmail.com

One response

Comments are closed.