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.
Examplepackage mainSyntaximport "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!")
}
func functionName(){Creating a Goroutine
// statements
}// Using `go` to run as a Goroutine
go functionName()
To create a Goroutine, prefix the function or method call with the go
keyword.
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!")
}
Hello, 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.
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")
}
Main Function Goroutine Active Goroutine Active Main Function Goroutine Active Main FunctionAnonymous Goroutines
Anonymous functions can also be run as Goroutines by using the go
keyword.
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.")
}
Hello from Anonymous Goroutine! Hello from Anonymous Goroutine! Hello from Anonymous Goroutine! Main function complete.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4