Nigiri
Nigiri

Reputation: 3639

About the order of channels

I ran the code below several times and sometimes "test" was printed after "test2".
Why is that?
I think "true" is sent to "test" first.

package main

import "log"
import "time"

func main() {
    test := make(chan bool, 1)
    test2 := make(chan bool, 1)

    go func() {
        for {
            select {
            case <-test:
                log.Println("test")
            case <-test2:
                log.Println("test2")
            }
        }
    }()

    time.Sleep(3 * time.Second)
    test <- true
    test2 <- true
    time.Sleep(1)
}

Edited 2014/7/27:
After reading the article, I think that each of "test <- true" and "test2 <- true" could be "happens-before" or "happens-after" or also "happens-concurrently".

Upvotes: 0

Views: 65

Answers (1)

peterSO
peterSO

Reputation: 166598

"If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection." You are seeing a uniform pseudo-random selection.

The Go Programming Language Specification

Select statements

Execution of a "select" statement proceeds in several steps:

1) For all the cases in the statement, the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once, in source order, upon entering the "select" statement. The result is a set of channels to receive from or send to, and the corresponding values to send. Any side effects in that evaluation will occur irrespective of which (if any) communication operation is selected to proceed. Expressions on the left-hand side of a RecvStmt with a short variable declaration or assignment are not yet evaluated.

2) If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.

3) Unless the selected case is the default case, the respective communication operation is executed.

4) If the selected case is a RecvStmt with a short variable declaration or an assignment, the left-hand side expressions are evaluated and the received value (or values) are assigned.

5) The statement list of the selected case is executed.

Since communication on nil channels can never proceed, a select with only nil channels and no default case blocks forever.

Upvotes: 1

Related Questions