SOUR-Monkey
2005.01.14, 07:47 PM
I am trying to make a socket connect() call timeout after a set period of time, rather than just sitting there doing nothing for hours if it is unable to connect. I was told to use setsockopt() with SO_SNDTIMEO and SO_RCVTIMEO to set a timeout, but as I expected it didn't affect the connect call.
My first thought after that was to set some sort of alarm, but because connect() just blocks if it can't make the connection, the entire thread locks up and I can't do anything until connect returns. A timer or alarm won't help me much.
So I decided to use multiple threads, and just terminate the connecting thread if it was taking too long. As I'm using Cocoa, I tried to use NSThread to do it but that doesn't appear to have a way to check the status of threads after they have been created. I could use POSIX threads, but that will get a little messy because it is with Obj-C classes.
Now for the questions: am I on the right track using threads to timeout, or am I just being stupid and missing another obvious solution? Have I missed something with NSThread that will allow me to track a threads progress and terminate it as necessary? And finally, if NSThread is as inflexible as I understand it to be (which I doubt), what alternatives are available? I've got no problem with writing my own threading class like NSThread, it would only have to be a wrapper for the POSIX calls. But I'd rather not :)
My first thought after that was to set some sort of alarm, but because connect() just blocks if it can't make the connection, the entire thread locks up and I can't do anything until connect returns. A timer or alarm won't help me much.
So I decided to use multiple threads, and just terminate the connecting thread if it was taking too long. As I'm using Cocoa, I tried to use NSThread to do it but that doesn't appear to have a way to check the status of threads after they have been created. I could use POSIX threads, but that will get a little messy because it is with Obj-C classes.
Now for the questions: am I on the right track using threads to timeout, or am I just being stupid and missing another obvious solution? Have I missed something with NSThread that will allow me to track a threads progress and terminate it as necessary? And finally, if NSThread is as inflexible as I understand it to be (which I doubt), what alternatives are available? I've got no problem with writing my own threading class like NSThread, it would only have to be a wrapper for the POSIX calls. But I'd rather not :)