带超时的多线程面向对象套接字代码
我们有一个很好的类,它建立一个套接字连接,然后重复连接它。 如果超时,我们想抛出异常。
我想要的是每个对象都有一个独立的超时。但是,正如其他帖子中所述,没有可移植的套接字超时代码。
我目前正在使用信号来实现,但这很丑陋,因为有一个全局变量指向当前对象。这意味着该代码不能是多线程的。
有没有办法以每个线程的方式建立一个计时器,以便每个对象都可以在自己的线程中运行?这似乎是最干净的方式。我可以构建一个队列,以便它们都在关键部分等待,但这非常难看,并且会影响多线程性能(而且我无论如何也不想这样做)。
We have a nice class that establishes a socket connection and then hits it repeatedly.
If it ever gets a timeout, we want to throw an exception.
What I'd like is an independent timeout for each object. However, as noted in other posts there is no portable socket timeout code.
I am currently doing it with a signal, but this is ugly, because there's a single global variable that points to the current object. This means this code could not be multithreaded.
Is there any way of establishing a timer in a per-thread way so that each object could run within its own thread? That seems the cleanest way. I could build a queue so that they all wait in a critical section, but that's extremely ugly and would impact multithreading performance (and I don't want to anyway).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过使用异步 I/O 来做到这一点。例如,使用
libevent
或asio
。只需在同一调度线程(I/O 服务)上启动读取操作和计时器即可。You can do that by using async I/O. For example, using
libevent
orasio
. Just fire up a read operation and a timer on the same dispatching thread (I/O service).