简体   繁体   中英

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 ).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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