Python Path: Thread pool

Source: Internet
Author: User

Version One

#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import Queue
Import threading


Class ThreadPool (object):

def __init__ (self, max_num=20):
Self.queue = Queue.queue (max_num)
For I in Xrange (max_num):
Self.queue.put (Threading. Thread)

def get_thread (self):
Return Self.queue.get ()

def add_thread (self):
Self.queue.put (Threading. Thread)

"""
Pool = ThreadPool (10)

def func (ARG, p):
Print arg
Import time
Time.sleep (2)
P.add_thread ()


For I in Xrange (30):
thread = Pool.get_thread ()
t = Thread (Target=func, args= (i, Pool))
T.start ()
"""

Version Two

From queue import queue
Import Contextlib
Import threading

Workerstop = Object ()


Class ThreadPool:

Workers = 0

Threadfactory = Threading. Thread
CurrentThread = Staticmethod (threading.currentthread)

def __init__ (self, maxthreads=20, Name=none):

SELF.Q = Queue (0)
Self.max = MaxThreads
Self.name = Name
Self.waiters = []
Self.working = []

def start (self):
While Self.workers<min(Self.max, Self.q.qsize () +len (self.working)):
Self.startaworker ()

def startaworker (self):
Self.workers +
= 1
name= "poolthread-%s-%s"% (Self.name or ID (self), self.workers)
Newthread
= Self.threadfactory (Target=self._worker,name=name)
Newthread.start ()

def callinthread (self, func, *args, **kw):
Self.callinthreadwithcallback (None, func, *args, **kw)

def callinthreadwithcallback (self, Onresult, func, *args, **kw):
o
= (func,args, KW, Onresult)
Self.q.put (o)


@contextlib. ContextManager
def _workerstate (self, StateList, workerthread):
Statelist.append (Workerthread)
Try
Yield
Finally
Statelist.remove (Workerthread)

def _worker (self):
CT
= Self.currentthread ()
o= Self.q.get ()
While o are not workerstop:
With Self._workerstate (self.working, CT):
function, args, Kwargs, Onresult
= O
del o
Try
Result
= function (*args,**kwargs)
Success
= True
except:
Success
= False
If Onresult is None:
Pass

Else
Pass

del function, args, Kwargs

If Onresult is not None:
Try
Onresult (success, result)
Except
#context. Call (CTX, Log.err)
Pass

del Onresult, result

With Self._workerstate (self.waiters, CT):
O
= Self.q.get ()

def Stop (self):
While Self.workers:
Self.q.put (Workerstop)
Self.workers-
= 1


"""
Def show (ARG):
Import time
Time.sleep (1)
Print arg


Pool
= ThreadPool (20)

For I in range (500):
Pool.callinthread (show, I)

Pool.start ()
Pool.stop ()
"""

Python Path: Thread pool

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.