gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
golang: example of goroutine
- User
golang: example of goroutine
- Assistant
Sure! In Go (Golang), a goroutine is a lightweight thread managed by the Go runtime. To create a goroutine, you simply prefix a function call with the
gokeyword. Here's a simple example that demonstrates how to use goroutines:package main import ( "fmt" "time" ) // Function that we will run as a goroutine func sayHello() { for i := 0; i < 5; i++ { time.Sleep(1 * time.Second) // Simulate some work fmt.Println("Hello from goroutine!") } } func main() { // Start the goroutine go sayHello() // Do some other work in the main thread for i := 0; i < 5; i++ { time.Sleep(2 * time.Second) // Simulate some work fmt.Println("Hello from main!") } // Wait for a second to ensure goroutine has time to finish time.Sleep(5 * time.Second) fmt.Println("Main function is exiting.") }