goroutines in golang explained
A goroutine is a lightweight thread of execution in Go. Goroutines are similar to threads in other programming languages, but they are multiplexed onto a smaller number of system threads, and they are managed by the Go runtime.
Goroutines are created by the go
keyword, followed by a function call. For example:
go myFunction()
Once a goroutine is created, it runs concurrently with the other goroutines in the same program. This means that it can run in parallel with other goroutines, or it can interleave its execution with other goroutines.
One of the main benefits of using goroutines is that they allow you to write concurrent and parallel code without dealing with the low-level details of threads, locks, and synchronization.
For example, you can use goroutines to perform many tasks concurrently, and then wait for all of the tasks to complete. Here is an example:
package main
import (
"fmt"
"time"
)
func printNumbers() {
for i := 1; i <= 10; i++ {
fmt.Printf("%d ", i)
time.Sleep(100 * time.Millisecond)
}
}
func printLetters() {
for i := 'A'; i <= 'J'; i++ {
fmt.Printf("%c ", i)
time.Sleep(100 * time.Millisecond)
}
}
func main() {
go printNumbers()
go printLetters()
time.Sleep(3000 * time.Millisecond)
}
In this example, the printNumbers
and printLetters
functions are run concurrently as goroutines and they will run simultaneously while the main goroutine sleep for 3 sec. the output of this program will be mixed numbers and letters that executed concurrently, without go
keyword it would've been executed sequentially.
Goroutines are executed in parallel with other goroutines and communicate by channels, also it is important to note that creating too many goroutines could affect the performance of the program, and should be used judiciously.