python-thread Pool

Source: Internet
Author: User

#!/usr/bin/env python#-*-coding:utf-8-*-ImportQueueImportThreadingImportContextlibImporttimestopevent= Object ()#A token that defines the meaning of a tag that exits after the task endsclassThreadPool (object):def __init__(self, max_num): Self.q= Queue. Queue ()#define a queue that is infinitely largeSelf.max_num = Max_num#define the maximum valueself.terminal= False#is defined as falseSelf.generate_list = []#How many processes are executingSelf.free_list = []#Define an idle list--Idle threads initialize various properties    defRun (self, func, args, callback=None):"""The thread pool performs a task:p Aram Func: Task function:p Aram args: task function required parameter:p Aram callback: callback function executed after task execution failed or succeeded, callback function There are two parameters 1, task function execution State, 2, Task function return value (default is None, that is: Do not execute callback function): return: If the thread pool has terminated, returns true otherwise none"""        ifLen (self.free_list) = = 0 andLen (self.generate_list) <Self.max_num:self.generate_thread () W=(func, args, callback,) Self.q.put (W)defGenerate_thread (self):"""Create a thread"""T= Threading. Thread (Target=self.call)#and execute the call methodT.start ()defCall (self):"""loop to get the task function and execute the task function"""Current_thread= Threading.currentthread#get the current threadSelf.generate_list.append (Current_thread)#adding to a thread queue that is in useEvent= Self.q.get ()#--Here is a get to the tuple w= () ....         whileEvent! =Stopevent:func, arguments, callback= Event#w= (func, args, callback)            Try: Result= Func (*arguments)#Perform task ret = AAA ()--def aaa (): Return 1Status =TrueexceptException as E:#If I have an error on this assignment ,Status =False Result=eifCallback is  notNone:#This is a return value                Try: Callback (status, result)exceptException as E:Passself.free_list.append (Current_thread)#---Remember to look at the context code, perform the task, put the thread in the free queueevent = Self.q.get ()#the current state should be no task, the thread waits for the task, does not endSelf.free_list.remove (Current_thread)#get task Remove break thread        Else:            ifevent =StopEvent:self.generate_list.remove (Current_thread)#remove the currently running thread, and when he finishes running    defClose (self): num=Len (self.generate_list) whilenum:self.q.put (stopevent)#num-= 1Import TimedefWork (i):Print(i) Pool= ThreadPool (10)#defines a maximum of 10 threads, instantiates, and initializes forIteminchRange (50):#50 Tasks createdPool.run (Func=work, args= (item,))#executes the work function, and args is the argumentpool.close ()#Close the thread poolUnderstanding the annotation thread pool
with Annotations

python-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.