python多线程之线程池

多线程的重要性不比多说。单反用到CPU密集型(处理中涉及大量计算)和IO密集型(处理中涉及大量读写,请求操作)的地方,都可能会用到多线程。

涉及到用多线程还是多进程看下这篇文章:http://blog.csdn.net/ruoyunliufeng/article/details/72677415




一、多线程
缺点:线程会一直增加,直到无法创建。每台机器支持最大创建线程数不同。

import threading
import time

def monitor_handle(i):
    print (threading.currentThread().getName())
    print i

while(1):
    thread_list = []    #线程存放列表

    for i in range(0,10):
        #创建
        m_t = threading.Thread(target=monitor_handle,args=(q))
        m_t.setDaemon(True)   #子线程随主线程的结束而结束
        thread_list.append(m_t)
    for t in thread_list:
        t.start()

    for t in thread_list:
        t.join()

    print("end")
    #延时
    time.sleep(1)



二、线程池
方法一:threadpool 模块
安装:pipy ,然后 python  setup.py install


 ##创建线程池
pool = threadpool.ThreadPool(1000)


while(1):
    ##0.创建一个线程用于数据操作
    thread_list = []    #线程存放列表

    test_list = []
    for i in range(100):
        test_list.append(i)
    ##3.创建N个线程进行读取操作
    request = threadpool.makeRequests(monitor_handle,test_list)
    [pool.putRequest(req)for req in request]
    # map( monitor_handle,request)    #也可以使用map方法,但我测试过速度和占用内存占用都不是很理想

    pool.wait()
    #延时
    time.sleep(5)




方法二:from multiprocessing.dummyimportPoolasThreadPool 模块
此方法要优于方法一,大家可以自行测试。


pool = ThreadPool(100)
for i in range(5):

    ##0.创建一个线程用于数据操作
    thread_list = []    #线程存放列表

    test_list = []
    for i in range(100):
        test_list.append(i)

    pool.map( monitor_handle,test_list)


    print("end")
    #延时
    time.sleep(5)

pool.close()  #关闭线程池,执行close后不会有新线程加入
pool.join()   #等待所有子线程结束掉,后再结束。



参考:
主要讲多线程的:http://python.jobbole.com/85050/
讲threadpool模块线程池的:           
http://blog.csdn.net/hehe123456zxc/article/details/52258358              
http://blog.csdn.net/hehe123456zxc/article/details/52258431





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若云流风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值