Exiting blocked threads (socket.accept)

Tim tim at unknownMailAddress.com
Wed Mar 27 10:51:54 PDT 2013


Hi guys,

I'm doing the following:

class Connection : Thread {
	private Socket pSocket;
	void run() {
		ptrdiff_t received;
		ubyte[0x10] buffer;

		mainloop:
		while(true) {
			received = pSocket.receive(buffer);

			// do some more stuff here
			if (buffer[0 .. received] == "QUIT")
				break mainloop;

		}
	}
	this(Socket s) {
		super(&run);
		pSocket = s;
	}
}

extern(C) void terminateServer(int s) {
	stopServer = true;
}

private bool stopServer = false;

void main() {

	sigaction_t sig;
	sig.sa_handler = &terminateServer;
	sigemptyset(&sig.sa_mask);
	sig.sa_flags = 0x00;
	sigaction(SIGINT, &sig, null);

	s.bind(new InternetAddress(2100));
	s.blocking(false);
	s.listen(0);

	while(!stopServer) {
		try
			(new Connection(s.accept)).start();
		catch (Exception e)
			Thread.yield();
	}

	s.shutdown(SocketShutdown.BOTH);
	s.close();
	
}

That works as expected, except the fact that pressing CTRL+C 
which stops the while(!stopServer) doesn't terminate the mainloop 
in my Connection-class (run()-method). This thread is blocked 
because of the receive()-method... but how can I force this 
thread to exit? Is there any chance to do that? I already tried 
to set the accepted socket to blocking(false) without any 
success...

Thanks in advance for any reply!


More information about the Digitalmars-d-learn mailing list