码迷,mamicode.com
首页 > 编程语言 > 详细

自己的线程池

时间:2016-07-20 22:43:57      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

注:Python中threading模块不像multiprocess模块有进程池,是没有线程池的,所以我们可以自己写一个线程池,此线程池的实现方式参照于twisted中的线程池实现方式。

实现线程池要解决的问题:

  1.线程池中初始化的线程数量------>取线程池最大线程数量和任务数中的最小值

  2.线程状态---->在某一个时刻一共有多少线程,有几个在运行,有几个在等待

  3.关闭线程

第一步:超简单的线程池

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import threading
import Queue
import time

class ThreadPool(object):
    def __init__(self,max_num=20):
        self.q = Queue.Queue(max_num)
        for i in xrange(max_num):
            self.q.put(threading.Thread)   // 这里往队列中加入的是类,不是对象
    #从线程池中取一个线程
    def get_thread(self):
        return self.q.get()

    #向线程池中添加一个线程
    def put_thread(self):
        self.q.put(threading.Thread)

Pool = ThreadPool(5)

def run(n,pool):
    print n
    time.sleep(2)
    pool.put_thread()

for i in xrange(10):
    thread = Pool.get_thread()
    t = thread(target = run,args=(i,Pool))
    t.start()

 

自己的线程池

标签:

原文地址:http://www.cnblogs.com/along1226/p/5689869.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!