Marius Anderie
Marius Anderie

Reputation: 33

SDL and C++: Waiting for multiple threads to finish

I am having trouble to fix the following problem: I have 10 threads that don't need to interact with each other and therefore can all run simultaneusly. I create them in a loop. However I need to wait until all threads are done until I can continue with the code that starts after the for loop. Here is the problem in pseudo code:

//start threads
for (until 10) {
    SDL_Thread* thread = SDL_CreateThread();
}
//the rest of the code starts here, all threads need to be done first

What's the best way to get this done?

I need to stay platform independent with that problem, that's why I try to only use SDL-functions.

If there is another platform independent solution for c++, I am fine with that too.

Upvotes: 0

Views: 1662

Answers (2)

Vimal
Vimal

Reputation: 456

You can take the following approach:

const int THREAD_COUNT = 10;
static int ThreadFunction(void *ptr);
{
    // Some useful work done by thread
    // Here it will sleep for 5 seconds and then exit
    sleep ( 5 );
    return 0;
}

int main()
{
   vector<SDL_Thread*> threadIdVector;

   // create 'n' threads
   for ( int count = 0; count < THREAD_COUNT; count++ )
   {
       SDL_Thread *thread;
       stringstream ss;
       ss << "Thread::" <<  count;
       string tname = ss.str();
       thread = SDL_CreateThread( ThreadFunction, tname, (void *)NULL);
       if ( NULL != thread )
       {
           threadIdVector.push_back ( thread );
       }
   }

   // iterate through the vector and wait for each thread
   int tcount  = 0;
   vector<SDL_Thread*>::iterator iter;
   for ( iter = threadIdVector.begin();
                 iter != threadIdVector.end(); iter++ )
   {
       int  threadReturnValue;
       cout << "Main waiting for Thread : " << tcount++ << endl;

       SDL_WaitThread( *iter, &threadReturnValue);
   }

   cout << "All Thread have finished execution. Main will proceed...." << endl;

  return 0;
}

I ran this program with standard posix libary commands and it worked fine. Then I replaced the posix library calls with SDL Calls. I do not have the SDL library so you may have to compile the code once. Hope this helps.

Upvotes: 2

ap0
ap0

Reputation: 1173

You can implement a Semaphor which increments for every running thread, if the thread is done it decrements the Semaphor and your main programm waits until it is 0.

There are plenty example how semaphore is implemented and by that it will be platform independent.

Upvotes: 1

Related Questions