简体   繁体   中英

C++: is it possible to make thread_local variable global?

For example, I have a thread_local variable in my code, but there are a set of functions, which access and modify it. For modularity, I took out them to a different translation unit (correct me if I'm wrong on terminology), by creating a header with their declarations and source file with their definitions.

// fun.h
int fun();
// fun.cpp
#include "fun.h"

int fun()
{
    // Modify the thread_local variable here
}
// main.cpp
#include "fun.h"

thread_local int var = 0;

int main()
{
    // Modify the var in the main
    var = 1;
    // Modify the var by calling the fun() from fun.h
    fun();
}

What to do? How to access it from fun() ? Isn't there a contradiction that global variables are common for all the threads of the process, but thread_local is local?

The variable var is already global. "Global" refers to the scope of the variable: it means it is declared in the outermost namespace, so its use is not restricted to a particular block, class, or sub-namespace. So a variable can be both global and thread-local without any contradiction.

All you're asking for is how to allow this global, thread-local variable to be accessed by other translation units. Well, one obvious solution is to declare fun as int fun(int& var) , so in main.cpp you would call it as fun(var) instead of just fun() . If you do that, you might not need a global variable, and your code will be easier to reason about. But I'm going to assume you have a good reason why you can't do that.

If that's the case, you should provide a declaration of the variable in fun.h :

extern thread_local int var;

Now every translation unit that includes fun.h is made aware of the existence of a global variable named var , which is of type int and has thread-local storage duration. It is assumed that one translation unit, somewhere in the program, will provide a definition of var , and all other translation units are just referring to that variable. (Since it's a thread-local variable, this single definition creates a set of objects: one per thread.) In your case, that definition, thread_local int var = 0; , is in main.cpp .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM