您的位置:首页 > 编程语言 > Python开发

python多线程之限制同时运行的线程个数

2017-10-02 13:47 387 查看
# -*- coding: utf-8 -*-

from __future__ import unicode_literals,division

import random,time

import threading

__author__='坏小子'

class MyThreadPool():

    def __init__(self,fun,n=4):

        assert n>0

        self.n=n

        self.i=0

        

        self.fun=fun

        

        self.l=[]

        self.ev=threading.Event()

        self.ev.set()

        self.finished_ev=threading.Event()

        self.finished_ev.clear()

        self.i_lock=threading.Lock()

        self.ev_lock=threading.Lock()

    def put(self,x):

        self.l.append(x)

    def puts(self,l):

        for x in l:

            self.l.append(x)

    def start(self):

        if len(self.l)==0:

            return

        while self.l:

            x=self.l.pop(0)

            self.ev.wait()

            t=threading.Thread(target=self.fun, args=(x,))

            t_=threading.Thread(target=self.__start_a_thread, args=(t,))

            t_.start()

            self.i_lock.acquire()

            self.i+=1

            self.i_lock.release()

            if self.i>=self.n:

                self.ev_lock.acquire()

                self.ev.clear()

                self.ev_lock.release()

        self.__join()

        print 'thread pool finished'

    def __join(self):

        self.finished_ev.wait()

    def __start_a_thread(self,t):

        t.start()

        t.join()

        self.i_lock.acquire()

        self.i-=1

        if self.i<self.n:

            self.ev_lock.acquire()

            self.ev.set()

            self.ev_lock.release()

        self.i_lock.release()

        if len(self.l)==0:#如果这是最后一个任务

            self.finished_ev.set()

def test():

    rd=random.random

    

    def f(x):

        print x,'start'

        time.sleep(rd()*4)

        print x,'finished'

    

    l=range(10)

    

    tp=MyThreadPool(f,5)

    tp.put(l[0])

    tp.puts(l)

    tp.start()#然后程序会阻塞在这一句

    

    print 'all finished !'

test()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐