Ayse
Ayse

Reputation: 2764

Unable to create multiple threads using for loop

I am trying to create 3 threads using a for loop. Following is my code snippet:

DWORD WINAPI ThreadProc0(LPVOID param)
{
   return 0; 
}
DWORD WINAPI ThreadProc1(LPVOID param)
{
    return 0;
}
DWORD WINAPI ThreadProc2(LPVOID param)
{
    return 0;
}

int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
{
   DWORD threadId = 0;
   int max_number=1;
   //Start the threads
   typedef DWORD (WINAPI * THREADPROCFN)(LPVOID lpParameter);
   THREADPROCFN function[3] = {ThreadProc0,ThreadProc1,ThreadProc2} ;
   for (int i = 0; i < max_number; i++) 
   {
      CreateThread( NULL,
                    0,
                    (LPTHREAD_START_ROUTINE)&function[i],
                    (LPVOID) i,
                    0,
                    NULL
                   );
   }
}

The code is compiled successfully but when executed, the error is solution.exe has stopped working. When I Debug the code, I get the following error:

Unhandled exception at 0x0034fd00 in Solution.exe: 0xC0000005: Access violation.

Waiting for help.

Upvotes: 2

Views: 255

Answers (1)

ta.speot.is
ta.speot.is

Reputation: 27214

You likely want function[i] (the ith function pointer to a thread start routine) rather than &function[i] (a pointer to the ith function pointer to a thread start routine).

   typedef DWORD (WINAPI * THREADPROCFN)(LPVOID lpParameter);
   THREADPROCFN function[3] = {ThreadProc0,ThreadProc1,ThreadProc2} ;

   for (int i = 0; i < max_number; i++) 
   {
      CreateThread( NULL,
                    0,
                    //                      v Here!
                    (LPTHREAD_START_ROUTINE)&function[i],
                    (LPVOID) i,
                    0,
                    NULL
                   );
   }

Being less familiar with C++ than I used to be, I think that after changing that the cast to LPTHREAD_START_ROUTINE would become redundant.

Upvotes: 3

Related Questions