I have created 4 threads, but when i am executing this program I am getting this as output:
Thread #: 1
Thread #: 2
Thread #: 3
Thread #: 3
Thread #: 4
Thread #: 4
Thread #: 4
Thread #: 5
Thread #: 5
Thread #: 5
.
.
.
Thread #: 5
Thread #: 5
I have 2 questions:
- I have created only 4 thread so why is it showing thread #: 5
- All the 4 threads created should run sequentially but why is it running only the last created thread?
Source code:
#include<windows.h>
HANDLE ThreadHandle[4];
DWORD dwThreadId[4];
DWORD WINAPI ThreadFunction(LPVOID param)
{
while (1)
{
printf("Thread #: %d\n", *((int*)param));
}
Sleep(10);
return 0;
}
int main()
{
static int i = 0;
for (i = 1; i <= 4; i++)
{
ThreadHandle[i] = CreateThread(NULL, 0, ThreadFunction, (LPVOID)&i, 0, &dwThreadId[i]);
Sleep(10);
}
while (1)
{
Sleep(100);
}
return 0;
}
i
is a static variable - there's only one instance. You're passing its address to threads and dereferencing it every time you callprintf
. So when the main thread changes the value ofi
, all worker threads immediately see the new value. For that very reason you see thread #5 - that's the value ofi
once thefor()
loop ends.Instead of
(LPVOID)&i
, pass(LPVOID)i
, and inside the thread, use(int)param
instead of*((int*)param)
. Casting pointers to int and back is legal in C (albeit dangerous if misused).