Quantcast
Channel: MarsHut
Viewing all articles
Browse latest Browse all 6551

Clarification on http://tour.golang.org/#65

$
0
0
Hello GoNuts,

I have a friend that has been studying Go for a few days and has shown
interest in learning more.

He was asking me about tour.golang.org number 65:

http://tour.golang.org/#65

package main

import (
"fmt"
"time"

func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)

func main() {
go say("world")
say("hello")

As he was describing the code to me and wondering why the output to the
program always looked like:

hello
world
hello
world
hello
world
hello
world
hello
world

I told him without synchronization you can't guarantee the order that it
will print correctly (hello first, followed by world). Then his question
was why is it printing correctly every time then as well as on his computer
running Go locally?

So this brings me to the group. I still maintain that the execution order
can't be guaranteed here because go say("world") could theoretically happen
before say("hello") but I think this should perhaps be pointed out that
it's just a timing issue of the 2nd say() function starting up faster than
the first one run as a new Goroutine.

In other words, from an outsider perspective it almost looks as if example
number 65 is almost pointing out the fact that one can depend on this order
in this example.

Can someone help clarify,

Thanks in advance!

Viewing all articles
Browse latest Browse all 6551

Trending Articles