4 ms·
Why does this race? After setting done = true, is there no guarantee that the goroutine will complete before the for loop ends?
by gophergopher 8y ago
Why does this race?
After setting done = true, is there no guarantee that the goroutine will complete before the for loop ends?
- YZF 8y agothere's no guarantee, they are running potentially concurrently. So the same variable is accessed from two goroutines with no mutex.
- deleted 8y ago[deleted]
- icholy 8y agoThe assignment isn't guaranteed to be an atomic operation.
- dualogy 8y agoBut there are no concurrent writers to the bool, the `true` setting should thus "eventually succeed" and reading the bool must resolve to either false or true at every point. Sure: maybe the first read happening concurrently with the write won't read true yet but surely the next one or the one after must? Of course synchronization in-general is a must. But using a bool here with one writer and continuous-reading-until is probably the least-dangerous-of-possible-examples.. even a number or anything slicish incl strings combined with an operator other than equals would, in the same code-snippet length, make the dangers illustrable and live-observable when running even without `-race` =)
- junke 8y ago> Sure: maybe the first read happening concurrently with the write won't read true yet but surely the next one or the one after must? You are expecting the read operation to be done either before or after the write, which would be the case if atomicity was guaranteed. There might be ugly intermediate states, or maybe there aren't, but don't know because there are no guarantees. See also: http://preshing.com/20130618/atomic-vs-non-atomic-operations/ http://preshing.com/20130618/atomic-vs-non-atomic-operations...
- dualogy 8y ago> There might be ugly intermediate states In the general case: absolutely! In the above very specific setup as I outlined it (one bool, a single writer, a simple-waiting-for-that-single-write-loop) --- not. (Hence my point that another equally-tiny snippet might make the issue much more locally-reproducable-and-experienceable even without `-race`.)