等待多个事件 C++
是否有推荐的方法来等待多个输入。 例如,我希望我的程序能够接收来自 3 个源的输入:
监听线程条件,例如 pthread_cond_wait()
从标准输入获取数据,例如 getline()
监听套接字,例如accept()
完成的最佳方法是什么这? 我是否需要为每个不同的输入源分配一个线程? 谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
无需单独的线程等待
accept(2)
和stdin
- 此处使用poll/select
。 不要使用条件变量,而是在线程之间创建一个管道(如果我们谈论 CV,那么您已经拥有线程),在同一poll
中等待它,并在事件发生时写入它。No need for separate threads waiting for
accept(2)
andstdin
- usepoll/select
here. Instead of conditional variable, create a pipe between threads (you already have threads if we talk about CVs), wait on it in the samepoll
and write to it when the event happens.您可以使用
文件描述符,而无需使用多个线程>select(2)
系统调用。 您可以使用pthread_cond_timedwait
来等待具有超时的条件变量,这样您等待的时间就不会超过特定的时间。我认为想要同时等待条件变量或某种文件描述符是非常不寻常的——如果你绝对确定这就是你想要做的,那么你将不得不使用多个线程,其中一个线程调用
pthread_cond_wait
/pthread_cond_timedwait
,另一个线程调用select
或其他一些I/O函数。You can listen on multiple file descriptors without using multiple threads using the
select(2)
system call. You can usepthread_cond_timedwait
to wait on a condition variable with a timeout, such that you don't wait more than a particular amount of time.I think it's highly unusual to want to simultaneously wait on either a condition variable or a file descriptor of some sort -- if you're absolutely sure that that's what you want to do, you'll have to use multiple threads, with one thread calling either
pthread_cond_wait
/pthread_cond_timedwait
, and the other thread callingselect
or some other I/O function.在现代 Linux 上,最好的方法是根本不使用
pthread_cond_wait
。 只需使用 eventfd 即可,这将使您能够使用 select/poll/ 监听多个事件epoll。On modern Linux the best way to do this is not to use
pthread_cond_wait
at all. Just use eventfd instead, which will enable you to listen for multiple events using select/poll/epoll.对于单个线程来说,这三种不同的消息传递选项似乎是互斥的; 单个线程在等待线程条件时如何从 stdin 读取数据?
如果您确实不想生成三个线程,我能想到的唯一选择是以某种方式修改或参数化线程、流和套接字库以获取对同步对象的引用。
It certainly seems as though these three different messaging options are mutually exclusive for a single thread; how can a single thread read from stdin while it's waiting for a thread condition?
If you really don't want to spawn three threads, the only option I can fathom is somehow modifying or parameterizing the thread, stream, and socket libraries to take a reference to a synchronization object.