Java 中通过 Thread 使用实现多线程,Golang 通过 gorouting 实现多线程。那 Python 中如何实现多线程呢?本文介绍 python 通过 threadpool 和 threading 如何实现多线程。threadpool
已于 2015-10-30
停止维护。
threadpool 示例
pip3 install threadpool
# -*- coding: utf-8 -*-
import time
from datetime import datetime
import threadpool
def say_hello(someone):
print(f'Hello {someone}, datetime {datetime.now()}')
time.sleep(2)
if __name__ == '__main__':
name_list = ['aa', 'bb', 'cc', 'dd']
start_time = datetime.now()
# 定义线程池,指定线程数量
pool = threadpool.ThreadPool(2)
# 调用 makeRequests 创建并开启多线程的函数,以及函数相关参数和回调函数
requests = threadpool.makeRequests(say_hello, name_list)
# 将所有要运行多线程的请求扔进线程池
[pool.putRequest(req) for req in requests]
# # 等待所有线程完成后退出
pool.wait()
print(f'{datetime.now()-start_time} second')
Hello aa, datetime 2017-04-01 11:09:43.519736
Hello bb, datetime 2017-04-01 11:09:43.519838
Hello cc, datetime 2017-04-01 11:09:45.523500
Hello dd, datetime 2017-04-01 11:09:45.523574
0:00:04.006323 second