python 線程鎖

鎖是解決臨界區(qū)資源的問題,保證每一個線程訪問臨界資源的時候有全部的權(quán)利
一旦某個線程獲得鎖, 其它試圖獲取鎖的線程將被阻塞
acquire(blocking=True,timeout=-1) 加鎖。默認True阻塞,阻塞可以設(shè)置超時時間。非阻塞時成功獲取鎖返回True,否則返回False。
當blocking設(shè)置為False時,不阻塞,同一個鎖對象,其它線程可以重用,但最后都必須釋放。
如果設(shè)置為True(默認True),其它試圖調(diào)用鎖的線程將阻塞,并立即返回False。阻塞可以設(shè)置超時時間
import time
import threading
from threading import Thread, Lock

worker_list = []
lock = Lock()


def students(num):
    while True:
        lock.acquire()  # 添加線程鎖
        if len(worker_list) >= num:
            break
        time.sleep(0.001)
        worker_list.append(1)
        lock.release()  # 釋放線程鎖
        print('current_thread is {} worker_list = {}'.format(threading.current_thread().name, len(worker_list)))


def student(num):
    while True:
        with lock:
            if len(worker_list) >= num:
                break
            time.sleep(0.001)
            worker_list.append(1)
            print('current_thread is {} worker_list = {}'.format(threading.current_thread().name, len(worker_list)))


if __name__ == '__main__':
    for i in range(10):
        # Thread(target=students, name='stadent {}'.format(i), args=(1000,)).start()
        Thread(target=student, name='with {}'.format(i), args=(10000,)).start()
    time.sleep(3)
    print('完成作業(yè)的總數(shù)為: {}'.format(len(worker_list)))

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容