threads: Waiting for event & shutdown socket

Regan Heath regan at netmail.co.nz
Wed May 30 15:40:15 PDT 2007


Regan Heath Wrote:
> Benjamin Schulte Wrote:
> > Question 2:
> > 
> > I have the methods:
> > 
> > startServer( )
> > which creates a thread that runs the server and handles everything there.
> > 
> > closeServer( )
> > this should KILL the thread. Wherever it is at the moment.
> > 
> > 
> > the thread itself just has a structure like (it's a one-client-server, cause I never would need more in this case):
> > 
> > - create socket
> > - bind socket and listen
> > 
> > while( true )
> > {
> >   - accept
> >   - handle messages
> > }
> > 
> > 
> > 
> > And for the case, no user connected to the server it will block at "accept". When I call 'closeServer' it should close the thread, even if it's in the accept method.
> > 
> > Hopefully I was able to explain it a bit exactlier now. I know, I have a bad english ;)
> 
> You make the socket non-blocking and change your loop to something like:
> 
> while(true) {
>   try {
>     - accept
>     - handle messages
>   } catch(SocketAcceptException e) {
>     Sleep(1);  //prevent a hard-loop when there is no socket to accept
>   }
> }

Slight correction, your loop should be

while(!stopping) ..etc.

and closeServer should set stopping = true; and then wait for the thread to exit normally with join();

Regan




More information about the Digitalmars-d mailing list