Socket server + thread: cpu usage

Justin Whear via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Apr 29 10:39:52 PDT 2014


On Tue, 29 Apr 2014 17:16:32 +0000, Tim wrote:

> 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?

If you use blocking sockets, you should probably spawn a new thread for 
each client.  If you use non-blocking sockets, you need to use poll or 
select to wait for incoming connections or data.


More information about the Digitalmars-d-learn mailing list