串行并发打印

我试图同时打印,但无法弄清楚为什么它的串行,已经把代码放在下面


package main


import (

        "fmt"

        "sync"

)


func main() {

        fmt.Println("Hello, playground")

        var wg sync.WaitGroup

        wg.Add(2)

    go func(){

        for i := 0; i < 4; i++ {

                if i%2 == 0 {

                        fmt.Println("hi", i)

                }

        }

         wg.Done()

       }()

        go func() {


                for i := 0; i < 4; i++ {

                        if i%2 != 0 {

                                fmt.Println("g", i)

                        }


                }

                wg.Done()

        }()

        wg.Wait()

}

期望值是 hi0 g1 hi2 g3


但我得到


从 g 1 从 g 3 hi 0 hi 2


慕田峪7331174
浏览 81回答 1
1回答

qq_笑_17

如此小的函数不太可能演示并发性,因为第一个 goroutine 甚至可能在第二个函数开始之前或上下文切换发生之前完成。如果在循环中添加一个小的暂停,您将观察到交错:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sync"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; wg.Add(2)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < 4; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if i%2 == 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("hi", i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(10 * time.Millisecond)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; }()&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < 4; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if i%2 != 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("from g", i)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(10 * time.Millisecond)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; }()&nbsp; &nbsp; wg.Wait()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go