tags:

views:

46

answers:

3

I have an application which does some socket communication with some hardwares. Assume for the particular hardware i have an object and this object initiates a thread which listens on a particular port number say 5001 infinitely until a connection is established.

Now if i delete this obect is there anyway by which i can ensure that the thread that is listening on port number 5001 infinitely also gets destroyed.

So the problem is whenever a new object for the same device is created the old thread does not get destroyed and hence there are thread leaks.

+1  A: 

In Windows you could use WaitForSingleObject function to check whether thread exited (you can pass thread's handle to is as an argument). And you probably want to create event which will initiate thread's exit.

Kirill V. Lyadvinsky
Cant a thread handle be used to kill or delete a thread.
ckv
Also since the thread will be listening infinitey on the particular port number using accept socket function there is no way i can safely exit the thread.
ckv
You could use `TerminateThread` function to kill a thread, but it is an extreme measures.
Kirill V. Lyadvinsky
+1  A: 

You need to use non-blocking socket in this case. In case of blocking sockets, Accept() call blocks until there is a connection. You can use ioctlsocket to make a socket non blocking, and check for error code WSAEWOULDBLOCK from Accept() call. And of course modify your infinite loop to use WaitForSingleObject.

More info here

Jujjuru
A: 

Its probably worth setting a variable to say that the thread loop should exit and then sending some data to the socket. This will cause the socket to receive data, wake up, discover its time to exit and exit.

Goz