How golang starts a task, the main task returns, but the asynchronous task can continue to run. It is best to control the timeout of the task, such as through ctx control.
my code is
package main
import (
"fmt"
"time"
)
func asyncTask() {
fmt.Println("task start")
time.Sleep(2 * time.Second)
fmt.Println("task end")
}
func main() {
fmt.Println("main start ")
go asyncTask()
fmt.Println("task...")
time.Sleep(3 * time.Second)
fmt.Println("main end")
}
i hope the main function does not need to sleep. The task continues to run after returning.
When
mainexits, the program ends and all goroutines shut down.mainmust have a way to wait until all goroutines end. You're correct that there are better ways than sleeping; sleeping in concurrent code is a red flag. Here are some basic options.Simplest is to use a channel.
main makes a channel and passes it into the worker.
<-donecauses main to wait until there's something to read. Once worker is done, it sends a true value down the done channel (the value doesn't matter), main reads it and can continue.For more workers use WaitGroups.
main creates a sync.WaitGroup. Each time it starts a goroutine it adds 1 to the group. Each worker is wrapped in a goroutine which will call
wg.Donewhen the work is done subtracting 1 from the group.wg.Wait()will wait until the WaitGroup is back to 0 indicating all workers are done.