0
0
Goprogramming~5 mins

Goroutine lifecycle

Choose your learning style9 modes available
Introduction

Goroutines let your program do many things at once. Understanding their lifecycle helps you manage when they start, run, and stop.

When you want to run tasks at the same time, like downloading files while showing progress.
When you need to handle many user requests without waiting for each to finish.
When you want to perform background work without stopping the main program.
When you want to improve program speed by doing multiple jobs together.
Syntax
Go
go functionName()

Use the go keyword before a function call to start a goroutine.

The goroutine runs independently and does not block the main program.

Examples
This starts the sayHello function as a goroutine.
Go
go sayHello()
This starts an anonymous function as a goroutine.
Go
go func() {
    fmt.Println("Running in a goroutine")
}()
Sample Program

This program starts a goroutine that prints a message. The main function waits a little so the goroutine can finish before the program ends.

Go
package main

import (
    "fmt"
    "time"
)

func sayHello() {
    fmt.Println("Hello from goroutine")
}

func main() {
    go sayHello() // start goroutine
    time.Sleep(100 * time.Millisecond) // wait a bit to let goroutine run
    fmt.Println("Main function ends")
}
OutputSuccess
Important Notes

Goroutines run independently but may stop if the main program ends before they finish.

Use synchronization tools like channels or WaitGroups to wait for goroutines to complete.

Starting too many goroutines without control can use a lot of memory.

Summary

Goroutines let your program do many things at once.

Use go before a function call to start a goroutine.

Manage their lifecycle carefully to avoid unexpected program exits.