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

孤街醉人 提交于 2019-12-14 03:37:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/16331478/how-to-create-multiplethreads-each-with-different-threadproc-function-using-cr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!