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

How to change mapsforge street names in .map file

android map openstreetmap mapsforge

I downloaded a map file (.map) from mapsforge server,

Remove repetitive try/catch code

java web-services methods try-catch

I have the following code in many methods

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.