3 回答
TA贡献1788条经验 获得超4个赞
main()
程序执行从初始化主包开始,然后调用函数。 main
..当函数调用返回时,程序将退出。它不会等待其他的(非- main
)完成的大猩猩。
main()
SayHello()
func SayHello(done chan int) { for i := 0; i < 10; i++ { fmt.Print(i, " ") } if done != nil { done <- 0 // Signal that we're done }}func main() { SayHello(nil) // Passing nil: we don't want notification here done := make(chan int) go SayHello(done) <-done // Wait until done signal arrives}
func SayHello(done chan struct{}) { for i := 0; i < 10; i++ { fmt.Print(i, " ") } if done != nil { close(done) // Signal that we're done }}func main() { SayHello(nil) // Passing nil: we don't want notification here done := make(chan struct{}) go SayHello(done) <-done // A receive from a closed channel returns the zero value immediately}
注:
SayHello()
runtime.GOMAXPROCS(2)
SayHello()
SayHello()
runtime.GOMAXPROCS(2)done := make(chan struct{})go SayHello(done) // FIRST START goroutineSayHello(nil) // And then call SayHello() in the main goroutine<-done // Wait for completion
TA贡献1777条经验 获得超10个赞
WaitGroup
sync
SayHello
.
package mainimport ( "fmt" "sync")func SayHello() { for i := 0; i < 10; i++ { fmt.Print(i, " ") }}func main() { SayHello() var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() SayHello() }() wg.Wait()}
package mainimport ( "fmt" "math/rand" "sync" "time")func main() { var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func(fnScopeI int) { defer wg.Done() // next two strings are here just to show routines work simultaneously amt := time.Duration(rand.Intn(250)) time.Sleep(time.Millisecond * amt) fmt.Print(fnScopeI, " ") }(i) } wg.Wait()}
TA贡献1995条经验 获得超2个赞
main
sync.WaitGroup
main
main
.
runtime.Goexit()
main
GoExit终止了调用它的Goroutine。没有其他戈鲁丁受到影响。Goexport在终止Goroutine之前运行所有延迟的呼叫。因为GoExit并不是一种恐慌,所以那些延迟函数中的任何恢复调用都会返回零。
从主Goroutine调用GoExit将终止该Goroutine,而不需要主返回。由于FuncMain尚未返回,该程序将继续执行其他goroutines。如果其他所有的Goroutines退出,程序就会崩溃。
package mainimport ( "fmt" "runtime" "time")func f() { for i := 0; ; i++ { fmt.Println(i) time.Sleep(10 * time.Millisecond) }}func main() { go f() runtime.Goexit()}
fatal error: no goroutines (main called runtime.Goexit) - deadlock!
os.Exit
os.Exit(0)
package mainimport ( "fmt" "os" "runtime" "time")func f() { for i := 0; i < 10; i++ { fmt.Println(i) time.Sleep(10 * time.Millisecond) } os.Exit(0)}func main() { go f() runtime.Goexit()}
- 3 回答
- 0 关注
- 1255 浏览
添加回答
举报