Python threadpool 线程池使用

发布时间: 更新时间: 总字数:539 阅读时间:2m 作者: 分享 复制网址

Java 中通过 Thread 使用实现多线程,Golang 通过 gorouting 实现多线程。那 Python 中如何实现多线程呢?本文介绍 python 通过 threadpool 和 threading 如何实现多线程。threadpool 已于 2015-10-30 停止维护。

threadpool 示例

  • 依赖
pip3 install threadpool
  • test_threadpool.py
# -*- 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 示例

说明:

  • Python 的 threading 模块有个 current_thread() 函数,它永远返回当前线程的实例

  • 多线程中,所有变量都由所有线程共享。创建一个锁就是通过 threading.Lock() 来实现,使用方法是先 lock.acquire(),然后 lock.release(),并确保 lock.release() 是在 finally

  • test_threading.py

# -*- 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会单独创建内存空间来存储赋值
    • 即在不同的线程里面赋值不会相互覆盖
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数