2017-04-18 67 views
-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) 

回答

0

我希望你知道locks的目的。在你的情況下,如果你想處理鎖定異常,如could not obtain lock,那麼你可以使用鎖內try塊,並可以處理它。

我建議這樣做,因爲在諸如db transactions等重要任務中,最好在try塊內使用鎖,因爲您可以通過恢復db事務來處理鎖異常。因此,最好在try區塊中處理鎖定。