Multithreading program executing only last created thread?

202 Views Asked by At

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:

  1. I have created only 4 thread so why is it showing thread #: 5
  2. 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;
}
1

There are 1 best solutions below

0
On BEST ANSWER

i is a static variable - there's only one instance. You're passing its address to threads and dereferencing it every time you call printf. So when the main thread changes the value of i, all worker threads immediately see the new value. For that very reason you see thread #5 - that's the value of i once the for() 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).