basic threading

This commit is contained in:
Adam D. Ruppe 2012-02-05 19:56:53 -05:00
parent 5b38267e09
commit bedea1ec31
2 changed files with 48 additions and 14 deletions

21
httpd.d
View File

@ -89,29 +89,32 @@ class HttpdConnection(CustomCgi) : Connection /* if(is(CustomCgi : Cgi)) */ {
Cgi cgi;
try {
cgi = new CustomCgi(headers, data, peerAddress(),
cast(void delegate(const(ubyte)[])) &this.write);
cgi = new CustomCgi(headers, data, peerAddress(),
cast(void delegate(const(ubyte)[])) &this.write);
} catch(Throwable t) {
write("HTTP/1.1 400 Bad Request\r\n");
write("Content-Type: text/plain\r\n");
string s = t.toString();
write("Content-Length: "~to!string(s.length)~"\r\n");
write("Connection: close\r\n");
write("\r\n");
write(t.toString());
write(s);
closeConnection = true;
return;
}
try {
handler(cgi);
scope(exit) {
cgi.close();
cgi.dispose();
}
try {
handler(cgi);
} catch(Throwable e) {
cgi.setResponseStatus("500 Internal Server Error");
cgi.write(e.toString());
cgi.close();
cgi.dispose();
return;
}
}

View File

@ -54,7 +54,7 @@ class ConnectionException : Exception {
class NetworkManager {
// you might want to override this to construct subclasses of connection
protected:
Connection allocConnection(int port){
Connection allocConnection(int port) {
if(auto a = port in allocs)
return (*a)();
assert(0);
@ -266,10 +266,19 @@ setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, on.sizeof);
if(s == -1)
throw new Exception("accept");
auto con = allocConnection(c.port);
con.parentManager = this;
addConnection(con, s, addr, c.port);
con.onRemoteConnect();
version(threaded_connections) {
auto con = allocConnection(c.port);
con.socket = s;
con.addr = addr;
con.port = c.port;
auto t = new ConnectionThread(con);
t.start();
} else {
auto con = allocConnection(c.port);
con.parentManager = this;
addConnection(con, s, addr, c.port);
con.onRemoteConnect();
}
}
}
@ -476,3 +485,25 @@ int now() {
return cast(int) getUTCtime();
}
version(threaded_connections) {
import core.thread;
import std.stdio : writeln;
class ConnectionThread : Thread {
Connection connection;
this(Connection c) {
connection = c;
super(&run);
}
void run() {
scope(exit)
connection.disconnectNow();
auto manager = new NetworkManager();
connection.parentManager = manager;
manager.addConnection(connection, connection.socket, connection.addr, connection.port);
while(manager.proceed()) {}
}
}
}