pthreads的 - 加入对线程组,等待一到退出 [英] pthreads - Join on group of threads, wait for one to exit

查看:100
本文介绍了pthreads的 - 加入对线程组,等待一到退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在POSIX线程接口,在pthread_join(线程)可以用来阻塞,直到指定线程退出。

In the POSIX thread interface, pthread_join(thread) can be used to block until the specified thread exits.

是否有类似的功能,将允许执行阻塞,直到所有子线程退出?

Is there a similar function that will allow execution to block until any child thread exits?

这是类似于的wait() UNIX系统调用,除适用于子线程,而不是一个过程。

This would be similar to the wait() UNIX system call, except be applicable for child threads, not a processes

推荐答案

我不认为这是pthreads的本身直接可能,但你可以解决它很容易。

I don't think this is directly possible from pthreads per se, but you can work around it fairly easily.

使用pthreads的API,你可以使用调用pthread_cond_wait 和朋友成立了状态,等待就可以了。当一个线程即将退出,信号状态的唤醒等待线程。

Using the pthreads API, you can use pthread_cond_wait and friends to set up a "condition" and wait on it. When a thread is about to exit, signal the condition to wakeup the waiting thread.

此外,另一种方法是创建管道管道,当一个线程将要退出,到管道。有主线程等待与管道要么选择调查的另一端epoll的或其自己喜欢的变体。 (这也可以让你同时等待其他文件描述符。)

Alternatively, another method is to create a pipe with pipe, and when a thread is going to exit, write to the pipe. Have the main thread waiting on the other end of the pipe with either select, poll, epoll, or your favorite variant thereof. (This also allows you to wait simultaneously on other FDs.)

的Linux新版本还包括做同样的事情eventfds,见男人eventfd ,但要注意这是最近才加入。请注意,是不是POSIX,它仅支持Linux的,如果你是合理了最新的才能使用它。 (2.6.22或更高)。

Newer versions of Linux also include "eventfds" for doing the same thing, see man eventfd, but note this is only recently added. Note that is isn't POSIX, it's Linux-only, and it's only available if you're reasonably up-to-date. (2.6.22 or better.)

我个人一直想知道为什么这个API的设计不是把这些东西类似于文件描述符。如果是我的话,他们会eventables,你可以选择文件,线程,定时器......

I've personally always wondered why this API wasn't designed to treat these things similar to file descriptors. If it were me, they'd be "eventables", and you could select files, threads, timers...

这篇关于pthreads的 - 加入对线程组,等待一到退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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