Go channels: why two different outputs? -


i'm trying understand channels in go. here code example:

package main  import "fmt"  func main() {     m := make(map[int]string)     m[2] = "first value"     c := make(chan bool)     go func() {         m[2] = "second value"         c <- true     }()     fmt.printf("1-%s\n", m[2])     fmt.printf("2-%s\n", m[2])     _ = <-c     fmt.printf("3-%s\n", m[2])     fmt.printf("4-%s\n", m[2]) } 

sometimes output of above code (result 1):

1-first value 2-first value 3-second value 4-second value 

but got (result 2):

1-first value 2-second value 3-second value 4-second value 

after changing c := make(chan bool) c := make(chan bool, 1), same occurred: result 1, result 2.

why?

your results makes perfect sense. go routine run independent of each other, never know when go routine start executing. line

m[2] = "second value" 

is executed reflected on main go routine.

hence when above line executed between first , second print of program see result as

1-first value 2-second value 3-second value 4-second value 

when not see other one. before third print ensure other go routine finished.

just clear more if modify program little bit like

package main  import "fmt" import "time"  func main() {     m := make(map[int]string)     m[2] = "first value"     c := make(chan bool)     go func() {         m[2] = "second value"         c <- true     }()     time.sleep(time.second)     fmt.printf("1-%s\n", m[2])     fmt.printf("2-%s\n", m[2])     _ = <-c     fmt.printf("3-%s\n", m[2])     fmt.printf("4-%s\n", m[2]) } 

playground

you following output

1-second value 2-second value 3-second value 4-second value 

hope helps.


Comments

Popular posts from this blog

mysql - FireDac error 314 - but DLLs are in program directory -

git - How to list all releases of public repository with GitHub API V3 -

c++ - Getting C2512 "no default constructor" for `ClassA` error on the first parentheses of constructor for `ClassB`? -