import time, threading
from threading import Lock
def work(timer):
# 如果在函数内部找不到变量,就会向上寻找,main 函数属于向上的领域
with lock:
print('操作文件')
print('只要在with lock里,就是单线程')
print(f'线程名称名:{threading.current_thread().name}')
time.sleep(timer)
if __name__ == '__main__':
print('主线程开始')
lock = Lock() # 声明锁对象
lst = [threading.Thread(target=work, args=(2,)) for i in range(5)]
for t in lst:
# t 是一个线程对象
t.start()
for t in lst:
t.join()
print('主线程结束')
标签:__,lock,threading,lst,print,多线程
From: https://www.cnblogs.com/hacker-dvd/p/17537380.html