5

I have some experience with multithread programming under Linux (C/C++ & POSIX threads), however most obvious cases are sometimes very complicated.

I have several static constant variables (global and function local) in my code, can I access them simultaneously from multiple threads without using mutexes? Because I don't modify them it should be ok, but it's always better to ask.

I have to do heavy speed optimization, so even as fast operations as mutex lock/unlock are quite expensive for me, especially because my application is going to access these variables form long loops.

Goofy
  • 5,187
  • 5
  • 40
  • 56
  • 1
    Looks like a dupe of my earlier question http://stackoverflow.com/questions/2762803/thread-safety-of-read-only-memory-access, the answer to which was that it's perfectly safe to access static data without locking. – Edmund May 17 '10 at 09:53

3 Answers3

16

If you initialize them on just one thread and then never modify them, it should be ok to read them concurrently from multiple threads without mutexes etc.

  • 5
    +1, In case it is not obvious enough from the answer: the first call to a function with a constant static variable is not thread safe. – David Rodríguez - dribeas May 17 '10 at 10:22
  • @David: In fact, most compilers use double-check locking and synchronize initialization of function-scope static variables. For example, it is totally safe with gcc. –  Sep 07 '11 at 13:04
6

If you're only reading and not modifying you shouldn't need any locks

Andreas Brinck
  • 51,293
  • 14
  • 84
  • 114
0

I don't know about other architectures, but intel guarantees that all reads are atomic, however, if you do feel like adding some, use something like value = atomic_add(&variable,0);, this will force all writes then add 0 to the value then return the old value, which doesn't get changed

Necrolis
  • 25,836
  • 3
  • 63
  • 101