Goroutines - Concurrency in Golang
Last Updated :
29 Oct, 2024
Goroutines in Go let functions run concurrently, using less memory than traditional threads. Every Go program starts with a main Goroutine, and if it exits, all others stop.
Example
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!")
}
Syntax
func functionName(){
// statements
}
// Using `go` to run as a Goroutine
go functionName()
Creating a Goroutine
To create a Goroutine, prefix the function or method call with the go
keyword.
Syntax
func functionName(){
// statements
}
// Using `go` to run as a Goroutine
go functionName()
Example:
Go
package main
import "fmt"
func display(s string) {
for i := 0; i < 3; i++ {
fmt.Println(s)
}
}
func main() {
go display("Hello, Goroutine!") // Runs concurrently
display("Hello, Main!")
}
OutputHello, Main!
Hello, Main!
Hello, Main!
In this example, only the results from the display
function in the main Goroutine appear, as the program does not wait for the new Goroutine to complete. To synchronize, we can use time.Sleep()
to allow time for both Goroutines to execute.
Running Goroutines with Delay
Adding time.Sleep()
allows both the main and new Goroutine to execute fully.
Example:
Go
package main
import (
"fmt"
"time"
)
func display(s string) {
for i := 0; i < 3; i++ {
time.Sleep(500 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go display("Goroutine Active")
display("Main Function")
}
OutputMain Function
Goroutine Active
Goroutine Active
Main Function
Goroutine Active
Main Function
Anonymous Goroutines
Anonymous functions can also be run as Goroutines by using the go
keyword.
Syntax
go func(parameters) {
// function logic
}(arguments)
Example:
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.")
}
OutputHello from Anonymous Goroutine!
Hello from Anonymous Goroutine!
Hello from Anonymous Goroutine!
Main function complete.
Explore
Go Tutorial
2 min read
Overview
Fundamentals
Control Statements
Functions & Methods
Structure
Arrays
Slices
Strings
Pointers