线程锁使用示例
递归锁RLock
DEMO
# coding: utf-8
import random
import time
from threading import Thread, RLock
num1, num2 = 0, 0
lock = RLock()
st = time.time()
def downloader(num):
"""
测试下载器加锁的作用
使用方法: 打开锁内延时表示下载器加锁睡眠, 打开所外延时表示不加锁睡眠
不加主动延时两条线程耗时15.1s, 不加锁两条线程耗时20.2s, 加锁后两条线程耗时30.3s
"""
lock.acquire()
num += 1
time.sleep(1) # 下载任务固有耗时
# time.sleep(1) # 主动延时一秒并加锁
lock.release()
# time.sleep(1) # 主动延时一秒但不加锁
return num
def work1():
global num1
while num1 < 10:
num1 = downloader(num1)
print("线程1 第{}次下载任务".format(num1))
et = time.time()
print("线程1 cost:", et-st)
def work2():
global num2
while num1 < 5:
num2 = downloader(num2)
print("线程2 第{}次下载任务".format(num2))
et = time.time()
print("线程2 cost:", et-st)
if __name__ == '__main__':
t_list = []
t1 = Thread(target=work1)
t2 = Thread(target=work2)
t_list.append(t1)
t_list.append(t2)
for t in t_list:
t.start()
for t in t_list:
t.join()
print("total cost:", time.time()-st)