Goroutines Concurrency in Golang (original) (raw)

Last Updated : 4 Apr, 2026

Goroutines are lightweight threads managed by the Go programming language runtime that allow functions to run concurrently. They are more efficient than traditional OS threads because they require less memory and have faster startup time.

Every Go program starts with a main goroutine, and when it finishes execution, all other goroutines are terminated.

Syntax

func functionName() {
// statements
}
// Run as Goroutine
go functionName()

**Example: Demonstrates basic Goroutine execution where a function runs concurrently with the main function, but may not complete before the program exits.

Go `

package main import "fmt" func display(str string) { for i := 0; i < 3; i++ { fmt.Println(str) } }

func main() { go display("Hello, Goroutine!")// Runs concurrently display("Hello, Main!") }

`

Output

Hello, Main! Hello, Main! Hello, Main!

**Explanation:

Running Goroutines with Delay

To allow goroutines to complete, we can use time.Sleep(). **Example:

Go `

package main import ( "fmt" "time" )

func display(str string) { for i := 0; i < 3; i++ { fmt.Println(str) } }

func main() { go display("Hello, Goroutine!")

time.Sleep(time.Second)// Wait for goroutine
display("Hello, Main!")

}

`

**Output:

Hello, Goroutine!
Hello, Goroutine!
Hello, Goroutine!
Hello, Main!
Hello, Main!
Hello, Main!

Explanation:

Anonymous Goroutines

Anonymous functions can also run as Goroutines by using the 'go' keyword.

Syntax

go func(parameters) {
// function logic
}(arguments)

**Example: Shows an anonymous Goroutine with a delay using time.Sleep() to ensure it completes execution before the main function ends.

Go `

package main import ( "fmt" "time" ) func main() { go func(s string) { for i := 0; i < 3; i++ { fmt.Println(s) time.Sleep(500 * time.Millisecond) } }("Hello from Anonymous Goroutine!")

time.Sleep(2 * time.Second) // Allow Goroutine to finish
fmt.Println("Main function complete.")

}

`

Output

Hello from Anonymous Goroutine! Hello from Anonymous Goroutine! Hello from Anonymous Goroutine! Main function complete.

Advantages vs Disadvantages

Advantages Disadvantages
Lightweight and fast Hard to control execution order
Easy to use (go keyword) Requires synchronization
Efficient concurrency model Debugging can be tricky