Search code examples
c++cthread-local

Is it OK to have a thread-local variable with the same name as a non-thread-local variable?


I have a thread local variable envptr and variable that is not thread-local also called envptr. The latter variable is only used in a single thread whose running code does not see the thread-local variable declaration. The thread-local variable is used by different threads, each of which do not see nor need to see the declaration of the non-thread-local variable.

Is this scenario possible and produces defined behavior? I am using linux 32bit and 64bit on x86.


Solution

  • Are they the same variable, or not? In other words, what is their linkage?

    If it is external, then no. If it is internal, then it's OK unless the two definitions both occur in the same file.

    If there is no linkage, then there is no problem.

    Unless I've overlooked something, thread_local has no impact on linkage, so the usual rules apply (and defining the variable thread_local in one translation unit, and not in another, is a violation of the one-definition rule).

    I think there's a bug in the standard here, however. The standard (§7.1.1/1) says that "If thread_local appears in any declaration of a variable it shall be present in all declarations of that entity." There's no explicit statement that a diagnostic is not required, or that violation of this rule is undefined behavior, so a compiler is required to diagnose the error. Except that, of course, if you define at namespace scope:

    thread_local int i;
    

    in one translation unit, and:

    int i;
    

    in another, then the compiler probably can't diagnose the error (and I'm fairly sure the committee didn't want to require it). My guess is that the intent here is undefined behavior.