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

StackOverflow https://stackoverflow.com/questions/14486243

  •  17-01-2022
  •  | 
  •  

Question

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.

Was it helpful?

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.

OTHER TIPS

From your description it sounds like they're two distinct variables (neither one ever shadows the other) in which case it seems prefectly ok from a technical standpoint.

That said I would never suggest doing this because the most likely thing to happen is that someone will get confused about the meaning in future maintenance and will cause more problems trying to understand the code.

This should work, and produce correct behavior, as the variables are two distinct variables.

I would strongly recommend not doing this, as it will just make the software less maintainable. Whether or not this behavior is correct seems less important as how understandable the code will be - using the same variable name for two sets of data with vastly different behavior seems problematic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top