Re: static variables cannot be used in multithread functions?
F'up set to comp.os.ms-windows.programmer.win32, please do that yourself
next time.
BruceWho wrote:
Recently I am playing with multithread programming, and I find that we
cannot use static variables in thread function.
That's not true, but I think you're not precisely saying what you mean.
void func(void* szName)
{
// if this static is removed, then everything goes OK.
static int a = 1;
while(a<10)
{
printf("%s:%d\n", szName, a++);
}
}
Well, define "OK" first! The point is that a function-static var is a global
variable with a local scope, nothing else. So, like all globals, it is
shared between threads.
int main(int argc, char* argv[])
{
printf("thread1 starts\n");
_beginthread(func, 0, "t1");
printf("thread2 starts\n");
_beginthread(func, 0, "t2");
Sleep(5000);
return 0;
}
this is the output:
thread1 starts
thread2 starts
t1:1
t1:2
t1:3
t1:4
t1:5
t1:6
t1:7
t1:8
t1:9
Press any key to continue
Totally normal output for that program. Thread 1 increments 'a' to 10 before
thread 2 even gets a timeslice, so thread 2 doesn't do anything eventually.
Uli