Golang - Why does this race condition occur?

package main
import "fmt"

var quit chan int
var glo int

func test() {

func main() {
    glo = 0
    n := 10000
    quit = make(chan int, n)
    go test()
    for {
        quit <- 1

When I run the program above, the output is 10000, but when I assign a bigger number(such as 1000000) to n, the output will be a random number less than n.

I haven't called runtime.GOMAXPROCS(), so these two goroutines can't run parallelly. And when I use go run -race to detect race condition, there are not any race condition warnings.

Why does this race condition occur?


As there is no synchronisation between the main and test goroutines, you don't know at what point the fmt.Println call in test will happen.

When running with GOMAXPROCS = 1, the answer will essentially depend on when the scheduler decides to stop executing main and switch to test. The send operation within the loop is one point where the scheduler can switch over to another goroutine, so with enough iterations of the loop you'd expect test to get a chance to execute at some point. It isn't necessarily going to switch at the same iteration every run leading to the variation in results.

As for catching this with the race detector, it successfully catches the problem for me:

$ go run -race test.go
Read by goroutine 5:
      /../test.go:8 +0x6e

Previous write by main goroutine:
      /.../test.go:18 +0xfe

Goroutine 5 (running) created at:
      /.../test.go:15 +0x8f

Need Your Help

XCode fails to run AppCode project

xcode build compilation project appcode

I am writing this project using AppCode: https://github.com/AndrewShmig/ASASocialServices

Iterating through a list or tuple?

python list tuples

I've got some coordinates stored as a list. I'm iterating over the list and I want to write the coordinates in a KML file. So I should end up with something resembling the following:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.