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
threading.Thread 示例
说明:
# -*- coding: utf-8 -*-
# 创建全局ThreadLocal对象:
import threading
from datetime import datetime
localVal = threading.local()
localVal.val = "Main-Thread"
def print_func():
print(f'{datetime.now()} {localVal.val} in {threading.current_thread().name}')
def main_func(name):
# 赋值
localVal.val = name
print_func()
if __name__ == '__main__':
t1 = threading.Thread(target=main_func, args=('One',), name='Thread-One')
t2 = threading.Thread(target=main_func, args=('Two',), name='Thread-Two')
t1.start()
t2.start()
t1.join()
t2.join()
print(f'{datetime.now()} {localVal.val}')
2017-04-01 11:30:03.366336 One in Thread-One
2017-04-01 11:30:03.366475 Two in Thread-Two
2017-04-01 11:30:03.366545 Main-Thread
说明:
threading.local()
用来保存一个全局变量,但该全局变量只有在当前线程才能访问
localVal.val = name
储存一个变量 name
到当前线程
- 如果在
线程A
里面再次对localVal.val
进行赋值,那么线程A
会单独创建内存空间来存储赋值
- 即在不同的线程里面赋值不会相互覆盖