How Goroutines communicate to perform a common goal


Code constructs like “synchronized”,”Lock”,”wait()”,”notify()” are not new for us. From decades we are coding with similar Legacy constructs that play a key role in multithreading codes. The Legacy term! 🙂 Yes, you read it correctly! When you try similar code with Go, code is very precise, compact, friendly and superfast. Lets see why Go executes multithreading (let me correct here GREEN THREADs) code faster than others. Because there is no Thread concept in Go, instead it has Green Threads.

For deeper concepts connect me.Install Trust app and click arrow button on Home page to switch to business related services, click “Freelancer Professionals” –>“Mock Interviewers” then “Go” to connect me. If You also want to show your profile in app as a expert of any technology then create your Service Provider profile. If your matching technology is not available then on Home page click (?) and whatsapp Trust support team,we will add category within minutes.

Here I have illustrated how two Goroutines are communicating with each other through channel to print Odd and Even numbers alternatively. This may give you little insight if you are planning to write new microservices ( especially for very huge data processing and scalable products like IoT etc.. then you can think of Go!

 * @author Gyanendra
 * @Date : 02/03/20
package main

import (

func main() {

	numFlag := make(chan int)
	done := make(chan bool)
	go oddNumberRoutine(numFlag, done)
	go evenNumberRoutine(numFlag, done)

func oddNumberRoutine(numNeedToBePrinted chan int, printingCompleted chan bool) {

	for {
		v := <-numNeedToBePrinted
		if v >= 20 {
			printingCompleted <- true
		fmt.Println("Odd ==>", v)
		numNeedToBePrinted <- v + 1


func evenNumberRoutine(numNeedToBePrinted chan int, printingCompleted chan bool) {
	numNeedToBePrinted <- 1
	for {
		v := <-numNeedToBePrinted
		if v > 20 {
			printingCompleted <- true
		fmt.Println("Even ==>", v)
		numNeedToBePrinted <- v + 1


Odd ==> 1
Even ==> 2
Odd ==> 3
Even ==> 4
Odd ==> 5
Even ==> 6
Odd ==> 7
Even ==> 8
Odd ==> 9
Even ==> 10
Odd ==> 11
Even ==> 12
Odd ==> 13
Even ==> 14
Odd ==> 15
Even ==> 16
Odd ==> 17
Even ==> 18
Odd ==> 19
Even ==> 20

Get this code from my repo

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.