cwindowsmultithreadingwinapicreatethread

How to create multiplethreads each with different ThreadProc() function using CreateThread()


I have successfully created a single thread using CreateThread().

Now I want to create 'n' number of threads but each with a different ThreadProc().

I have tried the following code but using it, 'n' number of threads are created all performing the same task (since Threadproc() function af all threads is same.)

    //Start the threads
for (int i=1; i<= max_number; i++) 
{
CreateThread( NULL, //Choose default security
              0, //Default stack size
              (LPTHREAD_START_ROUTINE)&ThreadProc,
              //Routine to execute. I want this routine to be different each time as I want each  thread to perform a different functionality.
              (LPVOID) &i, //Thread parameter
              0, //Immediately run the thread
              &dwThreadId //Thread Id
            ) 
}

Is there any way I can create 'n' number of Threads each with a different Thread procedure?


Solution

  • Try this:

    DWORD WINAPI ThreadProc1(  LPVOID lpParameter)
    {
      ...
      return 0 ;
    }
    
    DWORD WINAPI ThreadProc2(  LPVOID lpParameter)
    {
      ...
      return 0 ;
    }
    
    ...
    
    typedef DWORD (WINAPI * THREADPROCFN)(LPVOID lpParameter);
    
    THREADPROCFN fntable[4] = {ThreadProc1, ThreadProc2, ...} ;
    
    //Start the threads
    for (int i = 0; i < max_number; i++) 
    {
      DWORD ThreadId ;
    
      CreateThread( NULL,
                    0,
                    (LPTHREAD_START_ROUTINE)fntable[i],
                    (LPVOID) i,
                    0,
                    &ThreadId
                  ) ;
    }
    

    This will start max_number threads with different thread procedures (TreadProc1, ThreadProc2, etc.) as defined in fntable.