Ending Threads

Started by
2 comments, last by dev578 17 years, 8 months ago
I have a thread that is created by CreateThread(). I am using it to accept network connections, right now the socket is a blocking socket, so accept waits for connections. Usually when I want to end threads, I set a bool and the thread returns zero from within itself, to my understanding this is the preferred way of doing so? Obviously in this thread I am going to run into problems because of accept. I can make it non-blocking and loop the crap out of it, it just seems illogical to make that many accept calls. I also thought of using TerminateThread, but MSDN seems to think otherwise: The TerminateThread and TerminateProcess functions should be used only in extreme circumstances. That made me laugh:) They suggest getting around this by WaitForSingleObject(), which is also a function and can't be called because it waits at accept. I'm not sure what to do. Is there something I'm missing? Thank you in advance Dev578
Advertisement
Personally, I would use select with the listening connection, with a sane timeout (~30 seconds?). It'd look akin to:
while(!quit && -1!=select(...,InSet,...,...,Timeout)){    if(ListeningSocket is in InSet){         accept(...);         // ...    }    // ...}


This would effectively accept as needed, and check every 30 seconds or so if the quit bool is set. select is a little weird to work with, but there's a number of threads in the Networking forum that can help.
Quote:Original post by dev578
I have a thread that is created by CreateThread(). I am using it to accept network connections, right now the socket is a blocking socket, so accept waits for connections. Usually when I want to end threads, I set a bool and the thread returns zero from within itself, to my understanding this is the preferred way of doing so? Obviously in this thread I am going to run into problems because of accept. I can make it non-blocking and loop the crap out of it, it just seems illogical to make that many accept calls. I also thought of using TerminateThread, but MSDN seems to think otherwise:

The TerminateThread and TerminateProcess functions should be used only in extreme circumstances.

That made me laugh:) They suggest getting around this by WaitForSingleObject(), which is also a function and can't be called because it waits at accept. I'm not sure what to do. Is there something I'm missing?

Thank you in advance

Dev578


Have you looked into ExitThread?



"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
Good idea, that is what I will do. Thank you.

Dev578

Edit: ExitThread() would have to be called from within the thread right? That is the problem I was having. select() seems like it will do the trick, although It might be a slight annoyance having to wait a potential maximum of 30/x seconds for the thread to end.

This topic is closed to new replies.

Advertisement