Blocking send and receive algorithm in Go
You have at least one bug.



The closure from your code:

package main

import (
    "fmt"
    "time"
)

func main() {
    for i := 0; i &lt; 7; i++ {
        go func() {
            x := i
            fmt.Printf("Sending successful. i=%v\n", x)
        }()
    }
    time.Sleep(4 * time.Second)
}


Output:

$ go run closure.go
Sending successful. i=7
Sending successful. i=7
Sending successful. i=7
Sending successful. i=7
Sending successful. i=7
Sending successful. i=7
Sending successful. i=7
$


The x := i statement is in the wrong place. It should be:

package main

import (
    "fmt"
    "time"
)

func main() {
    for i := 0; i &lt; 7; i++ {
        x := i
        go func() {
            fmt.Printf("Sending successful. i=%v\n", x)
        }()
    }
    time.Sleep(4 * time.Second)
}


Output:

$ go run closure.go
Sending successful. i=4
Sending successful. i=5
Sending successful. i=1
Sending successful. i=3
Sending successful. i=2
Sending successful. i=0
Sending successful. i=6
$




Reference:

Go: Frequently Asked Questions (FAQ)

What happens with closures running as
goroutines?