Using __thread in c++0x

 ̄綄美尐妖づ 提交于 2021-02-06 09:58:11

问题


I read that there was a new keyword in C++: it's __thread from what I've read.

All I know is that it's a keyword to be used like the static keyword but I know nothing else. Does this keyword just mean that, for instance, if a variable were declared like so:

__thread int foo;

then anything to do with that variable will be executed with a new thread?


回答1:


It's thread_local, not __thread. It's used to define variables which has storage duration of the thread.

thread_local is a new storage duration specifier added in C++0x. There are other storage duration : static, automatic and dynamic.

From this link:

thread local storage duration (C++11 feature). The variable is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the variable. Only variables declared thread_local have this storage duration.


I think the introduction of this keyword was made possible by introducing a standardized memory model in C++0x:

  • C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?



回答2:


From the Wikipedia article on "Thread-local storage":

Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread.

This is sometimes needed because normally all threads in a process share the same address space, which is sometimes undesirable.

And:

C++0x introduces the thread_local keyword. Aside that, various C++ compiler implementations provide specific ways to declare thread-local variables:

Sun Studio C/C++, IBM XL C/C++, GNU C and Intel C/C++ (Linux systems) use the syntax:

    __thread int number;

Visual C++, Intel C/C++ (Windows systems), Borland C++ Builder and Digital Mars C++ use the syntax:

    __declspec(thread) int number;

Borland C++ Builder also supports the syntax:

    int __thread number;

So, whilst __thread does exist in practice and on some systems, thread_local is the new, official, C++0x keyword that does the same thing.

Prefer it to non-standard __thread whenever you have access to C++0x.




回答3:


The keyword is called thread_local. It means that each thread has its own version of that variable.




回答4:


No, it does not mean that "anything to do with that variable will be executed with a new thread". It means that there will be a copy of the variable for each thread that exists, and each thread can only see its own copy of the variable.



来源:https://stackoverflow.com/questions/7047226/using-thread-in-c0x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!