A tricky question

Started by
4 comments, last by md_lasalle 17 years, 4 months ago
Hi all! I'm wondering if my approach to a problem is good, and if not, what could i do. Right now i'm spawning a thread wich connect() to a host. You probably all know that if the host is invalid, it can take a lot of time before connect() returns, and especially on Linux systems. What i do is i simply kill the thread after a certain amount of time. (TerminateProcess on Windows , pthread_cancel on Linux) My question is this, what's going on under the hood after i kill the thread ? is the connect() call ended aswell ? I could test this on Linux but not on Windows, and everything seems fine. I'm just not sure what happens with the system when a call to connect() is ended because of a thread terminating. I just dont want to make the system unstable since a lot of people is going to use my app. Maybe I'm worrying too much, can someone clarify this please ? Thank you
Advertisement
Killing threads is always a bad idea, because the threads may hold locks that do not get released.

Three better ideas are:

1) Close the socket you're connecting, from another thread. This will typically un-wedge the opening thread, and make it return with an error.

2) Send a signal to the thread that's blocking. This will typically un-wedge that thread, and return with an error in the thread.

3) Use non-blocking sockets, issue the connect(), and use select() with a time-out to wait for the connection.
enum Bool { True, False, FileNotFound };
Why not just wait for connect() to return, and terminate the thread if it failed? It's just sitting waiting for a hardware interrupt, it's not going to be using any CPU time. You may be able to set the internal timeout in some way if the default (I think it's either 30 or 60 seconds) is too long for you (Linux gurus?).
closing the socket like hplus recommended is in my opinion the best way to do it, i must try it tonight tho, because if i wait for connect to stop, it can take long...
The question is probably one of interactive responsiveness. If a connection takes more than, say, 5 seconds to establish itself, it's likely that the other end is either not awake, or that any attempt to actually have an interactive conversation with the other end will be futile. Thus, you might as well give up after that pre-determined time-out, even if connect() is still trying.
enum Bool { True, False, FileNotFound };
ok option 1) worked like a charm.

thank you hplus!

This topic is closed to new replies.

Advertisement