2014-08-30 171 views
0

我无法解决以下问题: 我有10个线程不需要彼此交互,因此都可以同时运行。 我在循环中创建它们。 但是,我需要等到所有线程都完成后,才能继续执行for循环之后的代码。 这里是伪代码的问题:SDL和C++:等待多线程完成

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

什么是完成这件事的最佳方式?

我需要保持与该问题无关的平台,这就是为什么我只尝试使用SDL函数。

如果还有另一个独立于C++的平台解决方案,那我也很好。

+0

如果你可以使用'C++ 11',你可以在'C++ 11'中查看线程支持:http://en.cppreference.com/w/cpp/thread – olevegard 2014-08-30 07:53:13

回答

2
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; 
} 

我用标准的POSIX库文件命令运行这个程序,它工作正常。然后,我用SDL呼叫替换了posix库调用。我没有SDL库,因此您可能需要编译一次代码。 希望这有助于。

+0

也许我错了,但是,如果第一个线程在最后一个线程启动之前完成,那么迭代时是否会错过某些线程?否则我真的很喜欢这种方法,因为它很简单。 – 2014-08-30 13:28:10

+0

@Marius这不会是一个问题。当主创建一个新线程时,它总是将其添加到向量中。因此,即使第一个线程在最后一个线程启动之前完成,两个线程指针都将被插入向量中。所以在迭代开始之前,矢量的大小保证为10。现在在迭代期间,如果第一个线程已经完成执行,等待调用将立即返回,主线程现在将等待下一个线程。所以main只会等待那个仍在执行的线程,而其他线程会立即返回,这是我们想要的。 – vchandra 2014-08-30 20:36:04

1

您可以实现Semaphor这增加了每个正在运行的线程,如果线程完成它递减Semaphor和你的主要PROGRAMM等待,直至为0。

有很多例子旗语是如何实现的,并通过它将独立于平台。