Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static const variables thread-safe?

I'm wondering whether static constant variables are thread-safe or not?

Example code snippet:

void foo(int n)
{
     static const char *a[] = {"foo","bar","egg","spam"};
     if( ... ) {
       ...
      }
}
like image 264
Nyan Avatar asked Jul 13 '10 11:07

Nyan


People also ask

Are const variables thread-safe?

const objects work well with thread-safety because they are immutable. Even if you share references to the const object, you won't need to have any locking mechanisms to protect accessing the const object. However, mutable objects are where most problems with thread-safety occur.

Are const functions thread-safe?

In conclusion, const does mean thread-safe from the Standard Library point of view. It is important to note that this is merely a contract and it won't be enforced by the compiler, if you break it you get undefined behavior and you are on your own.

Are static variables shared between threads?

Static variables are indeed shared between threads, but the changes made in one thread may not be visible to another thread immediately, making it seem like there are two copies of the variable.


1 Answers

To be really safe you should do

static char const*const a[]

this inhibits modification of the data and all the pointers in the table to be modified.

BTW, I prefer to write the const after the typename such that it is clear at a first glance to where the const applies, namely to the left of it.

like image 188
Jens Gustedt Avatar answered Sep 19 '22 06:09

Jens Gustedt