1

I am programming in go and using mutex lock to lock certain variables so they cannot be overwritten while being read.

This got me thinking. Since you can read a variable multiple times. Is there a scenario where you ever have to lock a constant variable?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Ian.V
  • 345
  • 3
  • 19
  • 1
    Can you change a constant? No. If you can't, may there be a case when it is being written and read at the same time? – icza May 30 '18 at 11:42
  • @icza This is why I was wondering it. Would there be a certain way it has a point of using it with a constant. Thank you for reacting and reading so fast! – Ian.V May 30 '18 at 11:43
  • 2
    "constant variable" is a contradiction in terms. – Jonathan Hall May 30 '18 at 13:16

2 Answers2

6

The rule is simple: if multiple goroutines access a variable concurrently, and at least one of the accesses is a write, then synchronization is required.

If we talk about constants, then there is no variable, and you cannot take the address of a constant (for details, see Find address of constant in go), so it is not possible to modify constant values.

You do not need any synchronization to access constants from multiple goroutines.

icza
  • 389,944
  • 63
  • 907
  • 827
0

If you talk about constants there is no need to use sync routines to access them (as @icza suggests).

But if you consider const as variable whose value cannot be changed once it has been assigned a value, then you should be careful because of golang memory model and happens before relationship.

n-canter
  • 268
  • 1
  • 11
  • This doesn't make any sense. A constant is a constant, not a variable, and its value is defined at compile time, not at run time. "if you consider const as variable" then you don't know what a constant is. – Adrian May 30 '18 at 14:59
  • There is a little misunderstanding caused by OPs "constant variable" term. That's why I added this "if you consider..." part. Meaning, that if you use variable as a constant then you can face some pitfalls. – n-canter May 30 '18 at 15:05