threading模块
python学习-threading模块
主要用法
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
'''
def test(ag1)
print(ag1)
thread = threading.Thread(target=test, name='testThread', args=(ag1,))
'''
# target 为 callable 对象,要调用的函数
# name 为线程的名字,默认为'Thread-N'形式
# args 为固定参数,kwargs 为可变参数
# daemon 表示当主线程结束时是否结束子线程,默认为 False 即不结束子线程
thread.setDaemon(True)
# 设置 daemon 属性
thread.current_thread().name
# 返回线程本身,并访问其 name 属性
thread.start()
# 启动 Thread 对象
thread.join(1.0)
# 阻塞自身所在的线程
# 即等待一个线程执行完毕,继续运行程序,可设置等待时间,此为 1 秒
thread.isAlive()
# 查询线程是否还在运行
模块示例
import threading
import time
import sys
def fun1(key): # 创建任务
sys.stdout.write('hello %s:%s \n' % (key, time.ctime()))
def main():
threads = []
keys = ['a', 'b', 'c'] # 参数列表
threads_count = len(keys) # 线程数
for i in range(threads_count): # 添加线程任务
t = threading.Thread(target=fun1, args=(key[i],))
threads.append(t)
for i in range(threads_count): # 开始所有线程任务
threads[i].start()
for i in range(threads_count): # 等待所有线程任务执行完毕
threads[i].join()
if __name__ == '__main__':
main()
'''
hello a:Mon Feb 15 16:59:09 2021
hello b:Mon Feb 15 16:59:09 2021
hello c:Mon Feb 15 16:59:09 2021
[Finished in 0.1s]
'''
# ex_2.py
def main():
q = queue.Queue()
for ef in files:
q.put(ef)
threads_count = 10 # 线程数
while True:
threads = []
for i in range(threads_count):
if q.empty():
break
else:
df = q.get()
t = threading.Thread(target=exp, args=(df,))
threads.append(t)
for i in range(len(threads)):
threads[i].start()
for i in range(len(threads)):
threads[i].join()
if q.empty():
break
详细请看https://blog.csdn.net/briblue/article/details/85101144