简体   繁体   English

从插座选择中突围

[英]breaking out from socket select

I have a loop which basically calls this every few seconds (after the timeout): 我有一个循环,基本上每隔几秒钟就会调用一次(超时后):

 while(true){

    if(finished)
       return;

    switch(select(FD_SETSIZE, &readfds, 0, 0, &tv)){
        case SOCKET_ERROR : report bad stuff etc; return;
        default : break;
    }

    // do stuff with the incoming connection
 }

So basically for every few seconds (which is specified by tv), it reactivates the listening. 因此,基本上每隔几秒钟(由电视指定),它就会重新启动监听。

This is run on thread B (not a main thread). 它在线程B(不是主线程)上运行。 There are times when I want to end this acceptor loop immediately from thread A (main thread), but seems like I have to wait until the time interval finishes.. 有时候我想立即从线程A(主线程)结束此受体循环,但是似乎我必须等到时间间隔结束。

Is there a way to disrupt the select function from another thread so thread B can quit instantly? 有没有办法破坏另一个线程的选择功能,以便线程B可以立即退出?

The easiest way is probably to use pipe(2) to create a pipe and add the read end to readfds . 最简单的方法可能是使用pipe(2)创建管道并将读取端添加到readfds When the other thread wants to interrupt the select() just write a byte to it, then consume it afterward. 当另一个线程想要中断select()只需向其写入一个字节,然后再使用它即可。

Yes, you create a connected pair of sockets. 是的,您创建了一对连接的插座。 Then thread B writes to one side of socket and thread A adds the other side socket to select. 然后线程B写入套接字的一侧,线程A添加另一侧套接字以进行选择。 So once B writes to socket A exits select, do not forget to read this byte from socket. 因此,一旦B对套接字A的写操作退出选择,就不要忘记从套接字读取此字节。

This is the most standard and common way to interrupt selects. 这是中断选择的最标准,最常用的方法。

Notes: 笔记:

Under Unix, use socketpair to create a pair of sockets, under windows it is little bit tricky but googling for Windows socketpair would give you samples of code. 在Unix下,使用socketpair创建一个组插座,窗下是有点棘手,但谷歌搜索的Windows socketpair会给你的代码示例。

Can't you just make the timeout sufficiently short (like 10ms or so?). 您能否仅使超时足够短(例如10毫秒左右)?

These "just create a dummy connection"-type solution seem sort of hacked. 这些“只是创建一个虚拟连接”类型的解决方案似乎有些黑。 I personally think that if an application is well designed, concurrent tasks never have to be interrupted forcefully, the just has worker check often enough (this is also a reason why boost.threads do not have a terminate function). 我个人认为,如果应用程序设计良好,则不必强制并发任务,而不必经常中断工作人员的检查(这也是boost.threads没有终止功能的原因)。

Edit Made this answer CV. 编辑使这个答案简历。 It is bad, but it might help other to understand why it is bad, which is explained in the comments. 这很糟糕,但可能有助于其他人了解为什么不好,这在​​注释中进行了解释。

You can use shutdown(Sock, SHUT_RDWR) call from main thread to come out of waiting select call which will also exit your another thread before the timeout so you don't need to wait till timeout expires. 您可以从主线程使用shutdown(Sock,SHUT_RDWR)调用来退出等待的选择调用,该选择调用也会在超时之前退出另一个线程,因此您无需等待超时到期。

cheers. 干杯。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM