引入
from concurrent.futures import ThreadPoolExecutor
一个简单的线程池使用案例
from concurrent.futures import ThreadPoolExecutor
import time
pool = ThreadPoolExecutor(10, 'Python')
def fun():
time.sleep(1)
print(1, end='')
if __name__ == '__main__':
# 列表推导式
[pool.submit(fun) for i in range(20) if True]
from concurrent.futures import ThreadPoolExecutor
import time
pool = ThreadPoolExecutor(10, 'Python')
def fun(arg1,arg2):
time.sleep(1)
print(arg1, end=' ')
print(arg2, end=' ')
if __name__ == '__main__':
# 列表推导式
[pool.submit(fun,i,i) for i in range(20) if True]
# 单个线程的执行
task = pool.submit(fun,'Hello','world')
# 判断任务执行状态
print(f'task status {task.done()}')
time.sleep(4)
print(f'task status {task.done()}')
# 获取结果的函数是阻塞的,所以他会等线程结束之后才会输出
print(task.result())
阻塞等待
print(task.result())
批量获取结果
for future in as_completed(all_task):
data = future.result()
阻塞主线程,等待执行结束再执行下一个业务
# 等待线程全部执行完毕
wait(pool.submit(fun,1,2),return_when=ALL_COMPLETED)
print('')
以上就是Python 线程池模块之多线程操作代码的详细内容,更多关于Python 线程池模块的资料请关注python博客其它相关文章!
Powered By python教程网 鲁ICP备18013710号
python博客 - 小白学python最友好的网站!