VOOZH about

URL: https://www.geeksforgeeks.org/go-language/goroutines-concurrency-in-golang/

⇱ Goroutines - Concurrency in Golang - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Goroutines - Concurrency in Golang

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.

  • Managed by Go runtime (not OS directly)
  • Enable easy concurrency using the go keyword
  • Multiple goroutines can run simultaneously

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.


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

Explanation:

  • go display(...) runs in a separate goroutine
  • display("Hello, Main!") runs in the main goroutine
  • The program may exit before the goroutine finishes

Running Goroutines with Delay

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

Output:

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

Explanation:

  • time.Sleep() pauses the main goroutine
  • This gives time for other goroutines to execute

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.


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

Advantages vs Disadvantages

AdvantagesDisadvantages
Lightweight and fastHard to control execution order
Easy to use (go keyword)Requires synchronization
Efficient concurrency modelDebugging can be tricky
Comment
Article Tags:

Explore