In this lesson, you’ll learn how to execute functions concurrently in Go using goroutines. By simply prefixing any function call with theDocumentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
go keyword, you can run the function as a separate goroutine.
Sequential Execution Example
The following example demonstrates a sequential program that calculates the square of an integer after a one-second delay:calculateSquare is executed one after the other, which accumulates a significant overall delay.
Running Functions Concurrently
To run the same task concurrently, simply add thego keyword before the function call. This launches each call to calculateSquare as a separate goroutine:
Although the elapsed time appears very short (e.g., 13 milliseconds), none of the squares are printed. This behavior occurs because the
main function completes and exits before the goroutines have finished executing.Ensuring Goroutines Complete Execution
A simple workaround to allow all goroutines to finish is by adding a delay in themain function using time.Sleep. For example, adding a two-second pause gives the goroutines enough time to complete:
Using
time.Sleep is not the most reliable method to wait for goroutines to complete. A better approach is to use synchronization primitives such as WaitGroups, which will be covered in an upcoming lesson.