Ceci est probablement une question rudimentaire, mais je suis novice en programmation Python et je ne suis pas entièrement sûr de la pratique correcte.Implémentation de verrouillage Python (avec module de thread)
Dois-je créer un seul objet de verrouillage (globalement ou en cours de transmission) et l'utiliser partout où j'ai besoin de verrouiller? Ou, devrais-je créer plusieurs instances de verrouillage dans chacune des classes où je vais les employer. Prenez ces 2 échantillons de code rudimentaire, quelle direction est la meilleure pour aller? La principale différence étant qu'une seule instance de verrou est utilisée dans les deux classes A et B dans la seconde, alors que plusieurs instances sont utilisées dans la première.
Exemple 1
class A():
def __init__(self, theList):
self.theList = theList
self.lock = threading.Lock()
def poll(self):
while True:
# do some stuff that eventually needs to work with theList
self.lock.acquire()
try:
self.theList.append(something)
finally:
self.lock.release()
class B(threading.Thread):
def __init__(self,theList):
self.theList = theList
self.lock = threading.Lock()
self.start()
def run(self):
while True:
# do some stuff that eventually needs to work with theList
self.lock.acquire()
try:
self.theList.remove(something)
finally:
self.lock.release()
if __name__ == "__main__":
aList = []
for x in range(10):
B(aList)
A(aList).poll()
Exemple 2
class A():
def __init__(self, theList,lock):
self.theList = theList
self.lock = lock
def poll(self):
while True:
# do some stuff that eventually needs to work with theList
self.lock.acquire()
try:
self.theList.append(something)
finally:
self.lock.release()
class B(threading.Thread):
def __init__(self,theList,lock):
self.theList = theList
self.lock = lock
self.start()
def run(self):
while True:
# do some stuff that eventually needs to work with theList
self.lock.acquire()
try:
self.theList.remove(something)
finally:
self.lock.release()
if __name__ == "__main__":
lock = threading.Lock()
aList = []
for x in range(10):
B(aList,lock)
A(aList,lock).poll()
Merci! C'est exactement l'aide que je cherchais! – Matty