等待多个事件C ++ [英] Waiting on multiple events C++
问题描述
是否有建议的方法来等待多个输入.例如,我希望我的程序能够接收来自3个来源的输入:
Is there a recommended way to wait on multiple inputs. For example I would like my program to be able to receive input from 3 sources:
在线程条件下收听,例如pthread_cond_wait()
Listen on a thread condition e.g. pthread_cond_wait()
从标准输入中获取数据,例如getline()
Take data from Standard input e.g. getline()
在套接字上收听,例如accept()
Listen on a socket e.g. accept()
完成此任务的最佳方法是什么?每个不同的输入源都需要一个线程吗?谢谢
What is the best way to accomplish this? Do I need a thread for each different input source? Thanks
推荐答案
使用 pthread_cond_timedwait
等待带有超时,这样您就不必等待超过特定时间的时间.
You can listen on multiple file descriptors without using multiple threads using the select(2)
system call. You can use pthread_cond_timedwait
to wait on a condition variable with a timeout, such that you don't wait more than a particular amount of time.
我认为同时等待条件变量或某种文件描述符是非常不寻常的-如果您完全确定要这样做,则必须使用多个线程,一个线程调用pthread_cond_wait
/pthread_cond_timedwait
,另一个线程调用select
或其他一些I/O函数.
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 calling select
or some other I/O function.
这篇关于等待多个事件C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!