全局锁被忽略?

2024-09-30 22:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用SimpleHTTPServer作为代理。我的程序过于简单,如下所示:

print_lock = Lock()

class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):

    def do_GET(self):
        displayABC()
        displayDEF()

    def do_POST(self):
        displayABC()

def displayABC():
    print_lock.acquire()

    print "A"
    print "B"
    print "C"

    print_lock.release()

def displayDEF():
    print_lock.acquire()

    print "D"
    print "E"
    print "F"

    print_lock.release()

httpd = SocketServer.ForkingTCPServer(('', 80), Proxy)
httpd.serve_forever()

由于许多请求传入速度非常快,因此display方法在请求之间重叠,即:

A
D   # -> Note that they are 'out of order' in the output
E
F
B
C
...

理想情况下,我希望所有印刷品都采用相同的方法,以相互遵循:

A
B   # -> Correct order
C
D
E
F
...

您可以在我尝试使用Lock()的代码中看到,这没有效果。我这样搜索,有一些类似的问题,但它们都涉及线程


Tags: 方法selflockreleasedeforderdohttpd