Python 多线程。MyLock.acquire(),锁应该放在哪里?
问候 在以下代码中,应在尝试之前或之后获取锁?哪个是有效的?代码运行良好,但是,我希望确保我的代码完全锁定了线程Python 多线程。MyLock.acquire(),锁应该放在哪里?,python,multithreading,Python,Multithreading,问候 在以下代码中,应在尝试之前或之后获取锁?哪个是有效的?代码运行良好,但是,我希望确保我的代码完全锁定了线程 def DoThis(name, repeat): global x, MyLock MyLock.acquire() try: print ("Thread ",name, "Has Acquired the LOCK") while repeat > 0: x = x * 2
def DoThis(name, repeat):
global x, MyLock
MyLock.acquire()
try:
print ("Thread ",name, "Has Acquired the LOCK")
while repeat > 0:
x = x * 2
print (" X = ", x)
repeat -= 1
except:
raise #raise exception
finally:
MyLock.release()
print("Thread ", name, "Has Released the LOCK")
def DoAfter(name, repeat):
global x, MyLock
MyLock.acquire()
try:
print ("Thread ",name, "Has Acquired the LOCK")
while repeat > 0:
x = x + 1
print (" X = ", x)
repeat -= 1
except:
raise #raise exception
finally:
MyLock.release()
print("Thread ", name, "Has Released the LOCK")
def main():
print("Hello World")
global x, MyLock
x = 2
MyLock = threading.Lock()
# My_Thread = threading.Thread(target = MyFunc)
# We can modify the previous line by adding a thread name
My_Thread_1 = threading.Thread(target = DoThis, args = ('My Thread 1',20))
My_Thread_1.start()
My_Thread_2 = threading.Thread(target = DoAfter, args = ('My Thread 2', 20))
My_Thread_2.start()
print ("Final X = ", x )
我希望您知道
锁的用途。在您的情况下,如果您想要处理锁异常,例如无法获得锁
,那么您可以在try块中使用lock并处理它
我之所以建议这样做,是因为在重要的工作中,例如db事务
最好在try块中使用锁,因为您可以通过还原db事务来处理锁异常。所以最好在try
块中处理锁