2011-09-20 38 views
-1

sc-> start_server运行一个无限循环,其中在线程中调用MyClass处理方法。 我该如何替换main中的while(true)语句,以便我的程序等待所有线程终止?C++ UNIX:线程:使主线程等待或休眠,直到处理结束 - 主线程不知道pthread_t参考

编辑:并行线程-lib的使用和主()不知道你要等待任何线程的pthread_t引用

THX

int main(int argc, char** argv) 
    { 

      SocketCommunication * sc = SocketCommunication::get_menu(); //Singleton 

      MyClass yay;  
      short port = 6644; 

      sc->start_server(port, &yay); 

      while(true); 

     return 0; 
    } 
+0

你正在使用什么线程库?并行线程? –

+0

是的,我使用pthreads,但main()不知道pthread_t引用 – JACKSONMEISTER

回答

0

使用join

+0

main()不知道pthread_t引用 – JACKSONMEISTER

+0

也许是SocketCommunication类呢?在其中创建一个等待关联线程终止的方法。 – Simon

+0

不,它也不知道它,它在其他层中更多是在架构下更多 – JACKSONMEISTER

3

通常的方法(在并行线程,至少)是:

  1. 您有几个pthread_t引用到正在运行的线程。
  2. 而不是最后你的while循环,你等待所有的线程完成类似于pthread_join(threadX, NULL);的东西。

在你的情况,我看不出有任何的API来获取线程,但一旦你运行(也许要求以某种方式sc)螺纹保持,代码是相似的。

编辑

如果你只是想等待一个条件,很容易与条件变量。假设你已经使用这些:

pthread_mutex_t end_mutex = PTHREAD_MUTEX_INITIALIZER; 
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; 
bool all_threads_done = false; // Signals that all the threads are finalized 

然后,在你main()就可以等着它:

pthread_mutex_lock(&end_mutex); 
while (!all_threads_done) 
    pthread_cond_wait(&condition_var, &end_mutex); 

wait将释放互斥锁在等待。然后,每个线程上,您必须具备以下条件:

// Do whatever the thread has to do... 
// ... 
// and then, at the end... 
pthread_mutex_lock(&end_mutex); 
if (no_more_threads()) // You have to figure this thing out to ensure no more threads 
    all_threads_done = true; 
pthread_cond_signal(&condition_var); 
pthread_mutex_unlock(&end_mutex); 

注意,最后,即使当你在做一个while,它不是一个忙等待,因为大部分的时间在主线程正在等待pthread_cond_wait,并在任何线程结束时被唤醒。

+0

main不知道pthread_t引用,那么等待信号如果线程终止并且主要捕获该信号,那么该怎么办?是可能的还是您有更好的解?? – JACKSONMEISTER

+0

是的。这也可以做到。看我的编辑。 –

+0

那么sc也不知道参考 - 它们在更下层,所以我认为信号发射会很好 - 或者你有另一个tipp? – JACKSONMEISTER