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 completionTA貢獻1777條經驗 獲得超10個贊
WaitGroupsyncSayHello.
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.WaitGroupmainmain.
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.Exitos.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 關注
- 1316 瀏覽
添加回答
舉報
