Socket server + thread: cpu usage

Tim via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 29 10:16:32 PDT 2014


Hi guys,

I've the following snipped:

TcpSocket oSocket = new TcpSocket(AddressFamily.INET);
oSocket.bind(new InternetAddress("127.0.0.1", 12345));
oSocket.blocking(false);
oSocket.listen(0);

while(true)
{
	try
	{
		Socket oRequestSocket = oSocket.accept();

		Request oRequest = new Request(oRequestSocket);
		oRequest.start(); // Start request thread
	}
	catch (SocketAcceptException oException)
	{
		Thread.yield();
	}
}

When I execute the code above, the while(true)-loop uses nearly 
100% (1 complete cpu). When I connect to the server multiple 
times (note that each Request-Thread has it's own 
while(oRequestSocket.isAlive)-loop) the cpu usage easily reaches 
120, 130... 200 and more cpu usage.

Is there anything I'm doing wrong? I don't want use blocking 
sockets... how to handle 100 or 1000 connections when the main 
server thread already consumes 1 cpu?


More information about the Digitalmars-d-learn mailing list