日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python?threading中lock的使用詳解_python

作者:鍋爐房劉大爺 ? 更新時間: 2022-12-21 編程語言

在多線程中使用lock可以讓多個線程在共享資源的時候不會“亂”,例如,創建多個線程,每個線程都往空列表l中添加一個數字并打印當前的列表l,如果不加鎖,就可能會這樣:

# encoding=utf8
import threading
import time
lock = threading.Lock()
l = []
 
def test1(n):
	lock.acquire()
	l.append(n)
	print l
	lock.release()
 
def test(n):
	l.append(n)
	print l
 
def main():
	for i in xrange(0, 10):
		th = threading.Thread(target=test, args=(i, ))
		th.start()
if __name__ == '__main__':
	main()

運行結果:

[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3][
0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4[, 05, , 16, , 27, ]3
, 4, 5, 6[, 07, , 18, ]2
, 3, 4, [50, , 61, , 72, , 83, , 94],?
5, 6, 7, 8, 9]

因為每個線程都在同時往l中添加一個數字(當前每個線程運行的是test函數),然后又可能在同時打印l,所以最后的結果看起來會有些“混亂”。

下面讓每個線程調用“test1”函數,看看結果如何:

[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

現在看起來就好多了,因為test1中每次像l中添加數字并打印之前,都先加了一把“鎖”,這樣就可以保證每次只有一個線程可以往l中添加數字,而不是同時往l里添加數字。

通過上面的結果比較可以知道,當多線程中需要“獨占資源”的時候,要使用鎖來控制,防止多個線程同時占用資源而出現其他異常。

使用鎖的時候就調用acquire()方法,以此告訴其他線程,我正在占用該資源,你們要等會;待使用資源后需要釋放資源的時候就調用release()方法,告訴其他線程,我已經完成使用該資源了,其他人可以過來使用了。

python threading Lock

這篇文章主要是通過代碼說明:

  • threading.Lock()不影響 multiprocessing
  • .threading.Lock()影響 threading.

代碼如下:

import threading
import time
from multiprocessing import Pool
_lock = threading.Lock()
def small_func(value):
    """
    添加線程鎖
    :param value:
    :return:
    """
    print(value)
    with _lock:
        time.sleep(5)
    return value
def no_small_func(value):
    """
    沒有線程鎖
    :param value:
    :return:
    """
    print(value)
    # with _lock:
    time.sleep(5)
    return value
def main():
    """
    multiprocessing 是基于進程的,因此線程鎖對其不影響,
    :return:
    """
    st = time.time()
    p = Pool(processes=4)
    value = p.map(func=small_func, iterable=range(4))
    et = time.time()
    print(f"all use time: {et - st}")
    print(value)
def main2():
    """
    threading 受到 線程鎖 影響
    :return:
    """
    st = time.time()
    thread_list = []
    for temp_value in range(4):
        t = threading.Thread(target=small_func, args=(temp_value,))
        t.start()
        thread_list.append(t)

    for i in thread_list:
        i.join()

    et = time.time()
    print(f"all use time: {et - st}")
    # print(value)
def main3():
    st = time.time()
    thread_list = []
    res = []
    for temp_value in range(4):
        # 不加線程鎖就行了
        t = threading.Thread(target=no_small_func, args=(temp_value,))
        t.start()
        thread_list.append(t)

    for i in thread_list:
        v = i.join()
        res.append(v)

    et = time.time()
    print(f"all use time: {et - st}")
    print(res)
if __name__ == '__main__':
    # main()
    # main2()
    main3()

原文鏈接:https://blog.csdn.net/u012067766/article/details/79733801

欄目分類
最近更新