import "fmt"
import "time"
func main() {
array := []int{1, 2, 3}
for _, num := range array {
go func() {
fmt.Println(fucknum)
}(fucknum)
time.Sleep(time.Nanosecond)
}
time.Sleep(time.Second)
}
Since there is a time.Sleep
within the for-loop, I was expecting the output to be 1 2 3
because of the yielding of execution at each time.Sleep
.
However, the output of this piece of code outputs 2 1 3
. And after I changed Nanosecond
to Microsecond
, it turns to be 1 2 3
.
For comparison, I also tested python3's asyncio
version in which I assume asyncio.call_soon
is equivalent to Go's non-IO coroutine.
import asyncio
loop = asyncio.get_event_loop()
async def test():
for i in range(1, 4):
# replace call_soon with asyncio.sleep(0) does not change the result
loop.call_soon(lambda : print(i))
await asyncio.sleep(0)
loop.run_until_complete(test())
And the outputs are always 1 2 3
(This output is the same as what I expected as I know that internally, functions scheduled by call_soon is simply added into a FIFO queue)
How to explain the behavior of the Go version?