Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Last active December 23, 2015 12:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorendorff/6639124 to your computer and use it in GitHub Desktop.
Save jorendorff/6639124 to your computer and use it in GitHub Desktop.
In Go, all goroutines can read and write the same global variables, or objects shared across threads, so data races are possible.
package main
import (
"fmt"
"time"
)
var k int
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s, k)
k++
}
}
func main() {
go say("world")
say("hello")
}
package main
import (
"fmt"
"time"
)
type Counter struct {
X int
}
func say(s string, c *Counter) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s, c.X)
c.X++
}
}
func main() {
c := &Counter{0}
go say("world", c)
say("hello", c)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment