Home > Mobile >  go concurrency prints serially
go concurrency prints serially

Time:09-25

i am trying to print concurrently but not able to figure out why its serial, have put the code below

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()
}

expectation is hi0 g1 hi2 g3

but i get

from g 1 from g 3 hi 0 hi 2

CodePudding user response:

Such a small function is less likely to demonstrate the concurrency, because the first goroutine may complete even before the second one starts, or before context switch happens. If you add a small pause to the loop, you will observe the interleaving:

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup
    wg.Add(2)
    go func() {
        for i := 0; i < 4; i   {
            if i%2 == 0 {
                fmt.Println("hi", i)
            }
            time.Sleep(10 * time.Millisecond)
        }
        wg.Done()
    }()
    go func() {
        for i := 0; i < 4; i   {
            if i%2 != 0 {
                fmt.Println("from g", i)
            }
            time.Sleep(10 * time.Millisecond)

        }
        wg.Done()
    }()
    wg.Wait()
}
  • Related