Scanf in multiple goroutines giving unexpected results

go

Solution

`fmt.Scanf` isn't an atomic operation. Here's the implementation : http://golang.org/src/pkg/fmt/scan.go#L1115

There's no semaphor, nothing preventing two parallel executions. So what happens is simply that the executions are really parallel, and as there's no buffering, any byte reading is an IO operation and thus a perfect time for the go scheduler to change goroutine.

Problem

I was simply experimenting in golang. I came across an interesting result. This is my code. ``` package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup var str1, str2 string wg.Add(2) go func() { fmt.Scanf("%s", &str1) wg.Done() }() go func() { fmt.Scanf("%s", &str2) wg.Done() }() wg.Wait() fmt.Printf("%s %s\n", str1, str2) } ``` I gave the following input. ``` beat it ``` I was expecting the result to be either ``` it beat ``` or ``` beat it ``` But I got. ``` eat bit ``` Can any one please help me figure out why it is so?

Original source