-1

let's say there is a variable named s is shared by a two go routines, r1 and r2, r1(the only writer) write to s periodically, while r2 read from it periodically. r1 started first and then r2.

if s is not protected by any kind of locks(including channels), does r2 can see any random value which is not wrote by r1? if that can happen? please tell me the reason, thanks!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
gaols
  • 341
  • 5
  • 13
  • 1
    Yes, that is possible, if for instance r2 sees a "torn write". See https://dave.cheney.net/tag/data-race for more. – torek Sep 22 '20 at 05:58
  • 1
    Such a program would be racy and could do whatever it want. You cannot argue about a racy program, it is just wrong. – Volker Sep 22 '20 at 06:05

1 Answers1

1

It won't be "random", but the actual value read depends entirely on what type it is, on your architecture, on how the compiler has re-ordered statements, and just timing. We call this undefined, not random.

Simple data types such as integers are read atomically on most architectures. So if s is a simple uint32, you might be ok, meaning that value might have been the one written by another goroutine.

Anything more complicated (or on some other architectures) will see a mix of old and new value. For yet other data types (eg: slices, maps), the actual data can be reallocated elsewhere in memory. The result is a mish-mash that was never written by another part of your program.

Marc
  • 19,394
  • 6
  • 47
  • 51