Doesn't go routine and the channels work in order of call?

Issue

Doesn’t go routine and the channels worked in the order they were called.

and go routine share values between the region variables?

main.go

var dataSendChannel = make(chan int)

func main() {
    a(dataSendChannel)
    time.Sleep(time.Second * 10)
    
}

func a(c chan<- int) {
    for i := 0; i < 1000; i++ {
        go b(dataSendChannel)
        c <- i
    }
}

func b(c <-chan int) {
    val := <-c
    fmt.Println(val)
}

output

> go run main.go
0
1  
54 
3  
61 
5  
6  
7  
8  
9  

Solution

Channels are ordered. Goroutines are not. Goroutines may run, or stall, more or less at random, whenever they are logically allowed to run. They must stop and wait whenever you force them to do so, e.g., by attempting to write on a full channel, or using a mutex.Lock() call on an already-locked mutex, or any of those sorts of things.

Your dataSendChannel is unbuffered, so an attempt to write to it will pause until some goroutine is actively attempting to read from it. Function a spins off one goroutine that will attempt one read (go b(...)), then writes and therefore waits for at least one reader to be reading. Function b immediately begins reading, waiting for data. This unblocks function a, which can now write some integer value. Function a can now spin off another instance of b, which begins reading; this may happen before, during, or after the b that got a value begins calling fmt.Println. This second instance of b must now wait for someone—which in this case is always function a, running the loop—to send another value, but a does that as quickly as it can. The second instance of b can now begin calling fmt.Println, but it might, mostly-randomly, not get a chance to do that yet. The first instance of b might already be in fmt.Println, or maybe it isn’t yet, and the second one might run first—or maybe both wait around for a while and a third instance of b spins up, reads some value from the channel, and so on.

There’s no guarantee which instance of b actually gets into fmt.Println when, so the values you see printed will come out in some semi-random order. If you want the various b instances to sequence themselves, they will need to do that somehow.

Answered By – torek

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.