Wednesday, June 29, 2022

GO's Concurrency - 1






 

We all know that GO is famous for "goroutines". They are one of the basic and important unit in GO. That's why it is very important to understand about goroutine and How they works.

When the GO process begins, by default it has at least one goroutine. You are not creating this default goroutine, it is by default gets created when you write main function. YES this default goroutine is nothing but main goroutine

Without spending much time, lets create our first simple go routine.

func main() {

    //Write some logic here

    go simpleGoRoutine()

    //continue with remaining code logic here
}

func simpleGoRoutine() {
    fmt.Println("I am running concurrently")
}

 You can simply place go keyword before function.

Lets look at other ways to create goroutines. We can also use anonymous functions.

func main() {

    //Write some logic here

    go func () {
        fmt.Println("I am running concurrently")
    } ();

    //continue with remaining code logic here
}

You can also assign function to variable and place go before variable.

func main() {

    //Write some logic here

    anotherway := func() {
        fmt.Println("I am running concurrently")
    }

    go anotherway()
   
    //continue with remaining code logic here
}

This is how we can use goroutine in GO and run code concurrently.

Lets dive bit more deeper into goroutines. What is actually goroutine. Is it thread or something else 😏

Wait internals are coming soon !!!

 



 

 

No comments :

Post a Comment