why it could not print value alternatively

Issue

I write an exit and syncqueue channel

expected print like as follows ,but not happened ,
will g1 or g2 print value continuously by two
I know unbuffered channel sync rule , but it seems I misunderstand it

g1 0 
g2 1 
g1 1
g2 1
g1 2
g2 2

go playground print alternatively code snippet

package main

import (
    "fmt"
)

func main() {
    exit := make(chan struct{})
    transfer := make(chan int)

    go func() {
        defer func() {
            close(exit)
        }()
        for i := 0; i < 20; i++ {
            transfer <- i
            fmt.Println("g1\t", i) // 1

        }
    }()

    go func() {
        for i := 0; i < 20; i++ {
            <-transfer
            fmt.Println("g2\t", i) // 3  4
        }
    }()
    <-exit
}

Solution

So when you use a unbuffered channel it is a blocking transaction; What happens is both the go routines are stopped at a point and need to do a transaction; As soon as the transaction happens; Both go routines can now move forward, The scheduler needs to decide which go routine will run first It is not a 100% chance that g1 and g2 will print in same order.

Answered By – Shubham Srivastava

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.