簡體   English   中英

如何在多線程情況下使用python線程鎖定模塊

[英]How can I use python threading lock module in multi-thread case

我試圖通過使用python threading.Lock()鎖定函數,但是事情沒有按預期發生。

#!/usr/bin/python
# -*- coding:utf-8 -*-

import time
import threading
# mutex = threading.Lock()


def within_mutex():
    print "###########in mutex############"
    n = 0
    while n<5:
        print "waiting ...", n
        n += 1
        time.sleep(1)
    print "##########end mutex############"

def check_thread(lock):
    print "~~~~~~~~~~~in thread~~~~~~~~~~~~"
    print "=====before mutex======", lock.locked()
    with lock:
        print "get mutex, trigger a new thread"
        print "=====in mutex======", lock.locked()
        within_mutex()
    print "=====after mutex======", lock.locked()
    print "~~~~~~~~~~~end thread~~~~~~~~~~~~"

def thread_test(lock):
    if not lock.locked():
        thread1 = threading.Thread(target=check_thread, args=(lock))
        thread1.start()
    print "End thread_test"
    return 11

if __name__ == '__main__':
    lock = threading.Lock()
    t1 = thread_test(lock)
    t2 = thread_test(lock)
    print "t1 = ",t1
    print "t2 = ",t2

如上面的代碼所示,我試圖將鎖傳遞給線程測試函數thread_test() ,如果未獲取鎖,則該鎖應觸發新線程check_thread ,否則應立即返回結果(即11)。

在我看來,在主函數中, t1 = thread_test(lock)應該觸發一個新線程,並進入check_thread ,而t2 = thread_test(lock)不應該觸發一個新線程, t2 = thread_test(lock)應該只直接返回11 。

但是,觸發了兩個線程,我不知道為什么? 似乎lock.locked()不起作用或在check_thread函數中, with lock模塊不起作用。

並且,如何解決此問題,因為在這種情況下,我只想觸發一個線程,我該如何with lock工作?

以上代碼的結果:

End thread_test
~~~~~~~~~~~in thread~~~~~~~~~~~~
=====before mutex====== False
get mutex, trigger a new thread
=====in mutex====== True
###########in mutex############
waiting ... 0
End thread_test
t1 =  11
t2 =  11
~~~~~~~~~~~in thread~~~~~~~~~~~~
=====before mutex====== True
waiting ... 1
waiting ... 2
waiting ... 3
waiting ... 4
##########end mutex############
=====after mutex====== True
~~~~~~~~~~~end thread~~~~~~~~~~~~
get mutex, trigger a new thread
=====in mutex====== True
###########in mutex############
waiting ... 0
waiting ... 1
waiting ... 2
waiting ... 3
waiting ... 4
##########end mutex############
=====after mutex====== False
~~~~~~~~~~~end thread~~~~~~~~~~~~
[Finished in 10.8s]

怎么了:

  1. thread1說鎖是免費的
  2. thread2說鎖是免費的(在thread1成功獲取鎖之前)
  3. thread1進入with lock ,從而獲得了鎖
  4. thread2也with lock輸入-它在內部嘗試調用lock.acquire並且默認行為是等待釋放鎖定。 由於鎖已被線程1阻塞,因此線程2被迫等待完成。
  5. 這就是為什么它們都運行的原因,即使您嘗試檢查if lock.locked() (請注意,您當前的代碼偶爾會僅運行一個線程)

解:

而不是依靠with lock ,使用顯式lock.acquire(False) ,然后lock.release()一旦你與執行完成。

傳遞參數False將更改獲取鎖的默認行為(請參閱文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM