非阻塞在pthread_join [英] Non-blocking pthread_join

查看:584
本文介绍了非阻塞在pthread_join的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编码一个多线程的服务器。如果一切关机推移,它应该全部由自己的线程退出,但有一个小的机会,一个线程获得stuck.In这种情况下,这将是方便的非-blocking加盟,使我可以做的。

I'm coding the shutdown of a multithreaded server.If everything goes as it should all the threads exit by their own, but there's a small chance that a thread gets stuck.In this case it would be convenient to have a non-blocking join so I could do.

是否有这样做非阻塞pthread_join函数的一种方式?
某种定时加入将是一件好事。

是这样的:


foreach thread do
  nb_pthread_join();
    if still running
      pthread_cancel();

我能想到的更多的情况下,一个非bloking加入将是有益的。

I can think more cases where a a non-bloking join would be useful.

,因为它似乎没有这样的功能,所以我已经codeD一种解决方法,但它并不像我想的那么简单。

As it seems there is no such a function so I have already coded a workaround, but it's not as simple as I would like.

推荐答案

正如其他人所指出的没有标准的pthread库提供非阻塞在pthread_join。

As others have pointed out there is not a non-blocking pthread_join available in the standard pthread libraries.

然而,由于您所陈述的问题(试图保证您的所有线程都已经退出的程序关机),不需要这样的功能。你可以简单地做到这一点:

However, given your stated problem (trying to guarantee that all of your threads have exited on program shutdown) such a function is not needed. You can simply do this:

int killed_threads = 0;
for(i = 0; i < num_threads; i++) {
   int return = pthread_cancel(threads[i]);
   if(return != ESRCH)
      killed_threads++;
}
if(killed_threads)
    printf("%d threads did not shutdown properly\n", killed_threads)
else
    printf("All threads exited successfully");

有什么错,呼吁所有线程pthread_cancel可以(终止或不),因此呼吁对所有的线程不会阻止,并保证线程退出(干净与否)。

There is nothing wrong with calling pthread_cancel on all of your threads (terminated or not) so calling that for all of your threads will not block and will guarantee thread exit (clean or not).

这应该有资格作为一个简单的解决方法。

That should qualify as a 'simple' workaround.

这篇关于非阻塞在pthread_join的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆