Re: static variables cannot be used in multithread functions?
BruceWho wrote:
Hi, all
Recently I am playing with multithread programming, and I find that we
cannot use static variables in thread function.The first thread can
start but the second just freeze. Could anybody tell me why?
#include "stdafx.h"
#include "process.h"
#include "windows.h"
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++);
Add
Sleep(100);
here, see if it makes any difference.
}
}
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
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask