3 回答

TA貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
main()
程序執(zhí)行從初始化主包開(kāi)始,然后調(diào)用函數(shù)。 main
..當(dāng)函數(shù)調(diào)用返回時(shí),程序?qū)⑼顺?。它不?huì)等待其他的(非- 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貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
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貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
main
sync.WaitGroup
main
main
.
runtime.Goexit()
main
GoExit終止了調(diào)用它的Goroutine。沒(méi)有其他戈魯丁受到影響。Goexport在終止Goroutine之前運(yùn)行所有延遲的呼叫。因?yàn)镚oExit并不是一種恐慌,所以那些延遲函數(shù)中的任何恢復(fù)調(diào)用都會(huì)返回零。
從主Goroutine調(diào)用GoExit將終止該Goroutine,而不需要主返回。由于FuncMain尚未返回,該程序?qū)⒗^續(xù)執(zhí)行其他goroutines。如果其他所有的Goroutines退出,程序就會(huì)崩潰。
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 關(guān)注
- 1296 瀏覽
添加回答
舉報(bào)