A kind of thread pool

I used to call CreateThread() for all my threads, and WaitForMultipleObjects(), an leave the routine.

To get somewhat faster code, I'd like to do a kind of thread pool. My thread pools are sometimes created, later used multiple times, and later destroyed (ie., there is not a single pool created at the begining of the program). Each thread in my thread pool call the same routine with different parameters, the number of threads is constant, and they always need to be launched at the same time.

What I do is as follows :

DWORD WINAPI runFunction(LPVOID p) {
   Thread* = (Thread*) p;
    while(true) {
      WaitForSingleObject(thread->awakeEvenHandle, INFINITE);
    return 0;

void ExecuteThreads(std::vector<Thread*> &threads) {
  HANDLE* waitingEvents = new HANDLE[threads.size()];
  for (int i=0; i<threads.size(); i++) {
      if (threads[i]->handle == NULL) {
        threads[i]->AwakeEventHandle = CreateEvent(NULL, true, false, "Awake");
        threads[i]->SleepingEventHandle = CreateEvent(NULL, true, false, "Sleeping");
        threads[i]->handle = CreateThread(NULL, 0. runFunction, (void*) threads[i], CREATE_SUSPENDED, NULL);
       waitingEvents[i] = threads[i]->SleepingEventHandle;
   WaitForMultipleObjects( threads.size(), waitingEvents, TRUE, INFINITE);

My class Thread has a destructor which calls CloseHandle for the HANDLEs SleepingEventHandle and AwakeEventHandle, and for the thread handle. The function Thread::run() is pure virtual, and it's up to the coder to inherit the Thread for an actual run() implementation.

As it, the code doesn't work . One reason is that when I don't need this pool anymore, the destructors of the Threads are called, but the runFunction cannot exits and this crashes (the pointer "thread" has been destroyed but is still used the the function). There are probably many other problems with my code.

How would you do it, in a simple manner ? Is-there an easy fix ? What problems will I encounter with this code ?



Why do you have to deal with such low level api functions? Have a look at boost::thread and boost::thread_group. Also there is a thread pool implementation works with boost::thread.

Now if your threads work for a short period of time, your system will have remarkable overhead with creating and signaling all those threads and events. ppl Task Parallelism or tbb::task are definitely the ways to go.

Need Your Help

Is there any way to load all UI controls before displaying? C# winform

c# winforms load splash

I have a complicate win form with lots of controls and bulky repaints, controls resizeing and positioning according to user screen, this causes the form to be shown while doing some rendering and

OpenERP How to use a domain filter on many2one field?

python filter openerp many-to-one openerp-7

I am new to OpenERP (v7) and am writing a module that extends the res.partner class and added the following two fields :