jim*_*jim 1 multithreading asynchronous go
在Java中,我可以让线程运行很长一段时间,我不需要保持在启动线程的函数内.
Goroutines,Go对Threads的回答似乎在我从启动例程的函数返回后停止运行.
如何使这些例程保持运行并从调用函数返回?
谢谢
web*_*rc2 10
够程也继续运行调用它们的函数退出后:游乐场
package main
import (
"fmt"
"time"
)
func countToTen() chan bool {
done := make(chan bool)
go func() {
for i := 0; i < 10; i++ {
time.Sleep(1 * time.Second)
fmt.Println(i)
}
done <- true
}()
return done
}
func main() {
done := countToTen()
fmt.Println("countToTen() exited")
// reading from the 'done' channel will block the main thread
// until there is something to read, which won't happen until
// countToTen()'s goroutine is finished
<-done
}
Run Code Online (Sandbox Code Playgroud)
请注意,我们需要阻止主线程直到countToTen()goroutine完成.如果我们不这样做,主线程将退出,所有其他goroutine将停止,即使他们还没有完成他们的任务.
你可以。
如果你想go-routine永远在后台运行,你需要有某种无限循环,并有某种优雅的停止机制,通常是通过通道。go-routine并通过其他函数调用,因此即使在其他函数终止后,您的程序go-routine仍将运行。
例如:
// Go routine which will run indefinitely.
// Unless you send a signal on quit channel.
func goroutine(quit chan bool) {
for {
select {
case <-quit:
fmt.Println("quit")
return
default:
fmt.Println("Do your thing")
}
}
}
// Go routine will still be running,
// after you return from this function.
func invoker() {
q := make(chan bool)
go goroutine(q)
}
Run Code Online (Sandbox Code Playgroud)
invoker在这里,当您想要启动 时,您可以调用go-routine. 即使invoker返回后,您的 go-routine 仍将在后台运行。
唯一的例外是,当main函数返回时go-routines,应用程序中的所有内容都将终止。