0

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")
    }
}
1
  • 1
    If you're looking for help the least you could do is title and tag your question in a descriptive manner. Commented Jun 26, 2012 at 15:57

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't think he was so much assuming an ordering, as hoping to see both processes operating concurrently, rather than apparently running one after the other. My guess is it was supposed to be a simple test to see the coolness of go routines. That being the case, a small sleep after each print would also probably do the trick, though it will obviously slow things down.
Sure, but for anyone who finds this question while trying to debug there goroutines it's useful advice so I threw it in.
3

Unsynchronized goroutines execute in a completely undefined order. If you want to print out something like

1 sheeps
2 sheeps
3 sheeps
....

in that exact order, then goroutines are the wrong way to do it. Concurrency works well when you don't care so much about the order in which things occur.

You could impose an order in your program through synchronization (locking a mutex around the fmt.Println calls or using a channel), but it's pointless since you could more easily just write code that uses a single goroutine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.