开发者

tiemout for a function that waits indefiinitely (like listen())

I'm not quite sure if it's possible to do what I'm about to ask so I thought I'd ask.

I have a multi-threaded program where threads share a memory block to communicate necessary information. One of the information is termination of threads where threads constantly check for this value and when the value is changed, they know it's time for pthread_exit(). One of the threads contains listen() function and it seems to wait indefinitely. This can be problematic if there are nobody who wants to make connection and the thread needs to exit but it can't check the value whether thread needs to terminate or not since it's stuck on listen() and can't move beyond.

while(1)
{
  listen();
  ...
  if(value == 1)
    pthread_exit(NULL);
}

My logic is something like that if it helps illustrate my point better. What I thought would solve the problem is to allow listen() to wait for a duration of time and if nothing happens, it moves on to next statem开发者_运维百科ent. Unfortunately, none of two args of listen() involves time limit. I'm not even sure if I'm going about the right way with multi-threaded programming, I'm not much experienced at all. So is this a good approach? Perhaps there is a better way to go about it? Thanks for any insightful comments.

EDIT: just to clarify a little, the reason listen() is in the while loop is that this is a server and will be connected to multiple clients at a time.


You should send a signal from the other thread (the one that changes the value to 1). It will make the listen function return with the EINTR error code.


You would set the socket to non-blocking, and wait for events using select/poll or similar - select/poll allows you to set a timeout.

Note that listen() doesn't block, it just marks the socket ready to handle incoming connecions - accept() would be the next step, that does block.


IIRC you need to set the timeout with setsockopt(), and check errno after listen() fails to see if it's a timeout or a serious error.

To me it seems that it should be doable to call listen() only once if you always use the same connection socket. But maybe you'll have the same problem with accept().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜