-1
問候..多線程。 MyLock.acquire(),應該在哪裏放置鎖?
在以下代碼中鎖應該在嘗試之前還是之後獲得?哪個有效?代碼工作正常,但是,我想確保我的代碼完全鎖定線程。
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)