When to use locks in a threaded Web-server

Thomas Weholt thomas at weholt.org
Sat Mar 23 12:42:54 EST 2002


I got a web-server project based on BaseHTTPServer using threads (
SocketServer.ThreadingMixin ). What do I have to do to make it "safe",
thread-wise? When do I have to aquire locks to set variables in a) the
webserver itself or b) in variables in the given requesthandler ??

I thought each request would be handled using a seperate thread using this
method, ie. no locking required for altering stuff inside the requesthandler
alone. Is this correct? Is each handler a fresh new instance of the custom
requesthandler-class?

My assumptions lead me to think that I only have to use locks when changing
things in the global thread, the webserver, both from the requesthandlers
and inside the thread itself, ie. if the webserver alters variables in the
webserver. Correct?

Below are some code to examplify :

The HTTP-server

class HTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
    def __init__(self, root, hostaddress, port, handler, static_folder =
None):
        BaseHTTPServer.HTTPServer.__init__(self, (hostaddress, port),
handler)
        self.var1 = 1

The custom requesthandler :

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def __init__(self):
        BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, ....)
        self.svar1 = 1

    def do_GET(self):
        # something
        self.server.var1 = 100
        self.svar1 = 100

What variables requires a lock to be safe? var1 in HTTPServer? svar1 in the
RequestHandler? Other situations I'll have to watch out for?

Any clues, hints etc. appreciated.

Best regards,
Thomas Weholt





More information about the Python-list mailing list