多线程的重要性不比多说。单反用到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