-4

I am working with Go concurrency and have the following code:

package main

import (
    "fmt"
    "runtime"
    "sync"
)

func main() {
    runtime.GOMAXPROCS(1)
    var wg sync.WaitGroup
    wg.Add(2)
    fmt.Println("Starting Goroutines")
    go func() {
        defer wg.Done()
        for count := 0; count < 3; count++ {
            for char := 'a'; char < 'a'+26; char++ {
                fmt.Printf("%c", char)
            }
        }
        fmt.Println()
    }()
    go func() {
        defer wg.Done()
        for count := 0; count < 3; count++ {
            for char := 'A'; char < 'A'+26; char++ {
                fmt.Printf("%c", char)
            }
        }
        fmt.Println()
    }()
    fmt.Println("Waiting to Finish")
    wg.Wait()
    fmt.Println("Terminating")
}

My output is:

Starting Goroutines
Waiting to Finish
ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
Terminating

My problem is I declare the first goroutine to display lower case letters and the second goroutine to display upper case letters. Shouldn't the output be lowercase first then uppercase?

Any explanation would be helpful.

NOTE: This code came from the Go In Action ebook and i didnt fully understand their explanation.

peterSO
  • 158,998
  • 31
  • 281
  • 276
somejkuser
  • 8,856
  • 20
  • 64
  • 130
  • 4
    The entire point of goroutines is that they are concurrent. The order you type them in your code has no influence on the order they are executed. – JimB Jun 14 '18 at 14:30
  • So many serial downvoters.... remember SO asks to please comment WHY you downvote as well.... – Lucas Jun 14 '18 at 15:09
  • 2
    Possible duplicate of [Golang channel output order](https://stackoverflow.com/questions/50654576/golang-channel-output-order) – Himanshu Jun 14 '18 at 15:14

1 Answers1

2

Your output can vary each time you execute the program. The execution order of go routines is not guaranteed. Therefore your output is not deterministic.

mbuechmann
  • 5,413
  • 5
  • 27
  • 40