Skip to main content

Command Palette

Search for a command to run...

Go Routines

Go Routines

Published
•3 min read•View as Markdown
K

Hi, friends. This is keerthi raja what I post here are my learnings. Thank you.

  • Go Routines help us to handling multiple tasks at the same time (concurrency)

  • It is lightweight thread, Managed by go Runtime.

  • Go Routine is cheap in terms of memory and Resource.

How to create Goroutine

We can start a Goroutine by Simple using go Keyword followed by a function call.

package main

import (
    "fmt"
    "time"
)

func myprint() {
    fmt.Println("Hello my Friend ")
}

func main() {
    go myprint() // Start a goroutine
    time.Sleep(1 * time.Second) // Give the goroutine time to run before the program exits
    fmt.Println("Main function")
}
  • go myprint() creates a new goroutine that runs the myprint() function.

  • The time.Sleep(1 * time.Second) is added to allow some time for the goroutine to finish before it goes to next program executions. Without this, the main program might exit before the goroutine runs.

  • The main function prints "Main function" and then exits, but the goroutine is still running in the background.

Goroutines and Concurrency

  • Goroutines run concurrently.

  • Go will manage the scheduling

  • your program will run multiple tasks "simultaneously,"

  • They share the same memory space.

package main

import (
    "fmt"
    "time"
)

func printMessage(msg string) {
    fmt.Println(msg)
}

func main() {
    go printMessage("Goroutine 1")
    go printMessage("Goroutine 2")
    go printMessage("Goroutine 3")

    // Sleep to allow goroutines to complete before main function exits
    time.Sleep(1 * time.Second)
    fmt.Println("Main function done")
}
  • Three goroutines are started simultaneously. Each one calls printMessage() with different arguments.

  • time.Sleep(1 * time.Second) ensures that the main function doesn't exit too soon, allowing the goroutines time to print their messages.

Synchronization of Goroutines

  • Instead of creating artificial wait in previous example (time.Sleep ), we use Wait Groups.

  • The sync package provides mechanisms to synchronize goroutines.

Wait for Goroutines to Finish (using sync.WaitGroup)

package main

import (
    "fmt"
    "sync"
    "time"
)

func printMessage(msg string, wg *sync.WaitGroup) {
    defer wg.Done() // Decrement the counter when the goroutine completes
    fmt.Println(msg)
}

func main() {
    var wg sync.WaitGroup
    wg.Add(3) // Set the number of goroutines to wait for

    go printMessage("Goroutine 1", &wg)
    go printMessage("Goroutine 2", &wg)
    go printMessage("Goroutine 3", &wg)

    wg.Wait() // Wait for all goroutines to finish
    fmt.Println("Main function done")
}
  • sync.WaitGroup is used to wait for multiple goroutines to finish.

  • wg.Add(3) sets the number of goroutines to wait .

  • Each goroutine calls wg.Done() when it finishes

  • which decrements the wait group counter.

  • wg.Wait() blocks the main function until all goroutines call Done()

  • Ensuring the main function doesn’t exit Before go Routine completes.

Goroutines with Channels

  • Goroutines often need to communicate with each other.

  • Go provides channels to pass data between goroutines safely.

  • Channels allow goroutines to synchronize and exchange information.

Using Channels for Communication Between Goroutines.

package main

import (
    "fmt"
)

func sendMessage(ch chan string) {
    ch <- "Hello from goroutine!" // Send message through channel
}

func main() {
    ch := make(chan string) // Create a new channel

    go sendMessage(ch) // Start the goroutine

    msg := <-ch // Receive the message from the channel
    fmt.Println("Received message:", msg)
}
  • A channel ch is created using make(chan string)

  • The goroutine sendMessage sends a message through the channel using ch <- "message"

  • The main function receives the message with <-ch and prints it.

  • Channels in Go can be bidirectional (can be used for both sending and receiving).

Conclusion:

  • Goroutines are functions or methods that run concurrently with other functions in Go.

  • Use the go keyword to start a goroutine.

  • Goroutines are lightweight and managed by the Go runtime.

  • Synchronize goroutines using sync.WaitGroup, and communicate with them using channels.

  • Concurrency are easy to achieve in Go thanks to goroutines and channels. It create’s illusion of parallelism.