Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...