static char const err_msg[] = "Hell has frozen over.";
For a while I thought it was fine to share const
variables like the one above between threads, but then it occurred to me that unless such variables both start and end exactly on a cacheline boundary, any adjacent non-const data could cause false sharing, leading to any of the performance penalties that tends to entail.
Whether that concern is valid would -I assume- depend on how the C language and/or compilers determine where space is allocated for static
(const
) variables; but nonetheless, to minimize the chances of false sharing I guess it's best to declare all static
variables as thread_local
in a multi-threading context, even if they are const
:
thread_local static char const err_msg[] = "Hell has frozen over.";
Can you corroborate this?
@MichaelDorgan mentioned there are platforms where "there is an additional cost associated with accessing thread local variable and a limit on how many can be declared". Any references corroborating that could affect my assumptions above.
@JonathanLeffler mentioned that const
variables tend be laid out in read-only memory regions, which would eliminate false sharing concerns. A follow-up question in that regard would then be: is this strictly platform dependent, or are there stronger guarantees available?