Goroutine: simple implementation

You might have heard about GoLang a lot in the recent years as it’s one of the latest & popular programming languages. There are a thousand reasons for learning GoLang. You can check one of my article on why I prefer GoLang over others here. One of them is Goroutine. It is a lightweight thread managed by Go Runtime, requires less heap memory that enables thousands of concurrent execution in modern multicore processor systems.

Implementation of goroutine is much easier in comperison to threads in other programming languages. go keyword followed by function name and parameters will start a new goroutine, i.e.

go function_name(parameters) //starts a new goroutine

It will execute the function concurrently using goroutine in Go Runtime.

GoLang Program to run a funtion concurrently with main function

package main
//importing required packages
import (
	"fmt"
	"time"
)
//function to execute in parallel
func funtion_to_execute(parameter string){
	for i := 10; i>0; i-- {
		time.Sleep(1 * time.Millisecond)
		fmt.Println(parameter)
	}
}
func main() {
  //execute in new thread
	go funtion_to_execute("in funtion_to_execute function")
  //execute rest of the statements in main function
	for i := 10; i>0; i-- {
		time.Sleep(1 * time.Millisecond)
		fmt.Println("in main funtion")
	}
}

output

in main funtion
in funtion_to_execute function
in main funtion
in funtion_to_execute function
in funtion_to_execute function
in main funtion
in main funtion
in funtion_to_execute function
in main funtion
in funtion_to_execute function
in main funtion
in funtion_to_execute function
in main funtion
in funtion_to_execute function
in main funtion
in funtion_to_execute function
in funtion_to_execute function
in main funtion
in main funtion

GoLang Program to run multiple funtions concurrently

package main
//importing required packages
import (
	"fmt"
	"time"
)

//function to execute in parallel
func funtion_to_execute(parameter string){
	for i := 5; i>0; i-- {
		time.Sleep(1 * time.Millisecond)
		fmt.Println(parameter)
	}
}

func main() {
	//execute in new thread
  	go funtion_to_execute("1st thread")
	//execute in new thread
	go funtion_to_execute("2nd thread")
	//execute in new thread
	go funtion_to_execute("3rd thread")
	
    //waiting for completion of 
	time.Sleep(100 * time.Millisecond)
	
}

output

2nd thread
1st thread
3rd thread
1st thread
2nd thread
3rd thread
2nd thread
3rd thread
1st thread
3rd thread
1st thread
2nd thread
1st thread
3rd thread
2nd thread

NOTE: GoRoutine runs on the same address space, so using shared memory might be hazardous without synchronization. The sync package provides useful primitives.

Share on Social Media
Mukuldeep Maiti

Mukuldeep Maiti

An unrecognized crazy being with random thoughts lost in unknown

You may also like...

Leave a Reply