in this code:
int foo() {
static int x;
}
is the x
global to all threads or local in each thread? Or does that depends on a compiler flag and/or the compiler, so I cannot really know what it is from the code?
Several questions (all of them independent from compiler and compiler flags and OS):
I guess that this is not in C++ itself. (Is it in C++0x?) Some Boost lib which can do this?
But to answer your question, any thread can access any global variable currently in scope. There is no notion of passing variables to a thread.
Thread-local storage (TLS) is a mechanism by which variables are allocated such that there is one instance of the variable per extant thread. The run-time model GCC uses to implement this originates in the IA-64 processor-specific ABI, but has since been migrated to other processors as well.
If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.
ThreadSafe threadSafe = new ThreadSafe(); for (int i = 0; i < 10; i++) { threadSafe. executor. execute(new MyRunnable(threadSafe)); } ... private static class MyRunnable implements Runnable { private final ThreadSafe threadSafe; public MyRunnable(ThreadSafe threadSafe) { this. threadSafe = threadSafe; } ...
x is global to all threads. Always, independent of compiler and/or its flags. Independent of whether this is in C++11 or C++03. So if you declare a regular global or static local variable, it will be shared between all threads.
In C++11 we will have the thread_local
keyword. Until then, you can use thread_specific_ptr from Boost.Thread.
Quick partial answers;
(Is it in C++0x?)
Yes. But depends on your compiler's C++0x support too.
Some Boost lib which can do this?
Boost.Threads. See thread local storage therein.
- How can I create a static variable which is global to all threads?
- How can I create a static variable which is local to each thread?
- How can I create a global variable which is global to all threads?
- How can I create a global variable which is local to each thread?
Note that typically, static refers to duration and global refers to scope.
C++0x thread constructors are variadic: You can pass any number (and type) of arguments. All of these are available to your std::thread
object.
#include <thread>
int main()
{
int foo = 42;
std::thread t(foo); // copies foo
std::thread s(&foo); // pass a pointer
t.join();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With