Sign in to follow this  
md_lasalle

A tricky question

Recommended Posts

md_lasalle    190
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

Share this post


Link to post
Share on other sites
hplus0603    11347
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.

Share this post


Link to post
Share on other sites
Bob Janova    769
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?).

Share this post


Link to post
Share on other sites
hplus0603    11347
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this