Python threading中lock的使用详解

在多线程中使用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

%s 个评论

要回复文章请先登录注册