简体   繁体   English

在Python中使用多线程将锁定机制作为全局/类作用域

[英]Locking mechanism as global / class scope with multithreading in Python

what is the difference between using the lock mechanism and variables as globals (outside class scope) or class variables (declared as in the question)? 将锁机制和变量用作全局变量(在类范围外)或类变量(在问题中声明)之间有什么区别? such as: 如:

class httpHandler(BaseHTTPRequestHandler):
    success = 0
    fails = 0
    statsLock = threading.Lock()
    def do_POST(self):
    ...
    httpHandler.statsLock.acquire()
    httpHandler.success += 1
    self.statsLock.release()
    return

or: 要么:

success = 0
fails = 0
statsLock = threading.Lock()
class httpHandler(BaseHTTPRequestHandler):

    def do_POST(self):
    ...
    statsLock.acquire()
    success += 1
    statsLock.release()
    return

There isn't much of a difference. 没有太大的区别。 Both ways will work. 两种方式都可以。 Globals are however messy and dangerous so I would stay away from that. 但是全局变量是混乱且危险的,因此我会避免这样做。

Both examples are the functionally same, but you should use "global" definition of variable in second example, because you modify the global variable success and without global, local copy of the variable will be created (see this or python global documentation ). 这两个示例在功能上是相同的,但是在第二个示例中,您应该使用变量的“全局”定义,因为您成功修改了全局变量,并且没有全局变量,将创建变量的本地副本(请参阅thispython全局文档 )。

def do_POST(self):
...
global success, fails, statsLock

statsLock.acquire()
success += 1    # THIS DOES NOT WORK WITHOUT GLOBAL
statsLock.release()
return

Anyway, I think that: 无论如何,我认为:

  • the class scoped variables will be slightly faster because of simplified variable lookup (someone should benchmark this!). 由于简化了变量查找(有人应该对此进行基准测试!),所以类范围的变量将稍快一些。
  • the global variables are more difficult to maintain because of "global" statement and because of polluting global scope. 由于“全局”语句和污染全局范围,因此更难以维护全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM