Strange behavior of go routine

Issue

I just tried the following code, but the result seems a little strange. It prints odd numbers first, and then even numbers. I’m really confused about it. I had hoped it outputs odd number and even number one after another, just like 1, 2, 3, 4… . Who can help me?

package main

import (
    "fmt"
    "time"
)

func main() {
    go sheep(1)
    go sheep(2)
    time.Sleep(100000)
}

func sheep(i int) {
    for ; ; i += 2 {
        fmt.Println(i,"sheeps")
    }
}

Solution

More than likely you are only running with one cpu thread. so it runs the first goroutine and then the second. If you tell go it can run on multiple threads then both will be able to run simultaneously provided the os has spare time on a cpu to do so. You can demonstrate this by setting GOMAXPROCS=2 before running your binary. Or you could try adding a runtime.Gosched() call in your sheep function and see if that triggers the runtime to allow the other goroutine to run.

In general though it’s better not to assume ordering semantics between operations in two goroutines unless you specify specific synchronization points using a sync.Mutex or communicating between them on channels.

Answered By – Jeremy Wall

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.