DEV Community

Cover image for How does Go Routine work?
Ganesh Kumar
Ganesh Kumar

Posted on

How does Go Routine work?

#go

Hello, I'm Ganesh. I'm building git-lrc, an AI code reviewer that runs on every commit. It is free, unlimited, and source-available on Github. Star Us to help devs discover the project. Do give it a try and share your feedback for improving the product.

Understanding Go R

What is a Go Routine?

Go Routine is a lightweight thread managed by the Go Scheduler. Any thread created by the Go Runtime is handled by the Go Scheduler.

Go Scheduler is a part of the Go Runtime that manages the execution of Go Routines. It is responsible for scheduling the execution of Go Routines and managing the state of the Go Routines.

In Other Programming Languages, each thread has a stack size of 256 KB to 1 MB. But in Go, each thread has a stack size of 2 KB to 4 kb.

How Concurrency Different From Parallelism?

Concurrency

It is mostly software based.
Is the ability of a program to perform multiple tasks at the same time.
It Focuses on reducing the execution time of a program.
It is exececuting tasks in a most effient order the order is not specified it depends on the scheduler.

Parallelism

It is mostly hardware based.
It is the ability of a processor to execute multiple instructions at the same time.
It truly executes tasks in parallel.

How to create a Go Routine?

Every Go Program executes in a main go routine.

Other go routines are created using go keyword.

package main

import "fmt"

func main() {
    go say("hello")
    say("world")
}
func say(word string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(word)
    }
}
Enter fullscreen mode Exit fullscreen mode

We can see that the output is not in order.

This is because the Go Scheduler is responsible for scheduling the execution of Go Routines and managing the state of the Go Routines.

We can't predict the output of the go routine.

Output:

gk@jarvis:~/exp/code/rd/go-exmaple$ go run main.go 
hello
world
world
hello
hello
world
world
hello
hello
world
gk@jarvis:~/exp/code/rd/go-exmaple$ go run main.go 
world
hello
hello
world
world
hello
hello
world
world
Enter fullscreen mode Exit fullscreen mode

Conclusion

In Next Article, we will see how to work with unordered events.

git-lrc

Any feedback or contributors are welcome! It’s online, source-available, and ready for anyone to use.
⭐ Star it on GitHub: https://github.com/HexmosTech/git-lrc

Top comments (0)