![]() |
VOOZH | about |
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.
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.
Hello, Main! Hello, Main! Hello, Main!
Explanation:
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:
Anonymous functions can also run as Goroutines by using the 'go' keyword.
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.
Hello from Anonymous Goroutine! Hello from Anonymous Goroutine! Hello from Anonymous Goroutine! Main function complete.
| Advantages | Disadvantages |
|---|---|
| Lightweight and fast | Hard to control execution order |
Easy to use (go keyword) | Requires synchronization |
| Efficient concurrency model | Debugging can be tricky |