Guest User

Threading / Concurrency Issue - D

a guest
Oct 23rd, 2013
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.40 KB | None | 0 0
  1. TcpSocket Server;
  2. Thread ReceiveThread;
  3. Connection[int] Connections;
  4.  
  5. void Start(string IPAddress, ushort Port)
  6. {
  7.     Server = new TcpSocket();
  8.     Server.bind(new InternetAddress(IPAddress, Port));
  9.     Server.listen(500);
  10.    
  11.     ReceiveThread = new Thread(&HandleReceive);
  12.     ReceiveThread.start();
  13.    
  14.     HandleAccept();
  15. }
  16.  
  17. void HandleAccept()
  18. {
  19.     while (true)
  20.     {
  21.         Socket connectedSocket = Server.accept();
  22.  
  23.         Connection conn = new Connection;
  24.         conn.socket = connectedSocket;
  25.        
  26.         synchronized
  27.         {
  28.             conn.key = GetKey();
  29.             Connections[conn.key] = conn;
  30.         }
  31.        
  32.         // it gets here and the connection is added to the collection ...
  33.        
  34.         Thread.sleep(dur!("msecs")( 1 ));
  35.     }
  36. }
  37.  
  38. void HandleReceive()
  39. {
  40.     while (true)
  41.     {
  42.         synchronized
  43.         {
  44.             // never loops ...
  45.             foreach (Connection conn; Connections.values)
  46.             {
  47.                 // doesn't even get here ...
  48.                 writeln("Handling ...");
  49.                 if (conn.Handled)
  50.                     continue;
  51.                 conn.Handled = true;
  52.  
  53.                 writeln("Receiving ...");
  54.                
  55.                 ubyte[] recBuffer = new ubyte[1024];
  56.                 int ReceiveSize = conn.socket.receive(recBuffer, SocketFlags.NONE);
  57.  
  58.                 writeln("Received ...");
  59.                
  60.                 conn.socket.send("Hello World!");
  61.  
  62.                 writeln("Send ...");
  63.                
  64.                 conn.socket.shutdown(SocketShutdown.BOTH);
  65.                 conn.socket.close();
  66.            
  67.                 Connections.remove(conn.key);
  68.  
  69.                 writeln("Removed ...");
  70.             }
  71.         }
  72.         Thread.sleep(dur!("msecs")( 1 ));
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment