Principle: Set up a task queue, then multiple threads are removed from the task queue and then executed, of course, the task queue to lock, detailed see code
Import Threadingimport timeimport Signalimport OS class Task_info (object): Def __init__ (self): Self.func = None sel F.parm0 = None Self.parm1 = None Self.parm2 = None class Task_list (object): Def __init__ (self): self.tl = [] Self.mutex = Threading. Lock () Self.sem = Threading. Semaphore (0) def append (self, ti): Self.mutex.acquire () self.tl.append (TI) self.mutex.release () SELF.SEM.R Elease () def fetch (self): Self.sem.acquire () self.mutex.acquire () Ti = Self.tl.pop (0) Self.mutex.relea SE () Return TI class Thrd (threading. Thread): Def __init__ (self, TL): Threading. Thread.__init__ (self) self.tl = TL def run (self): while True:tsk = Self.tl.fetch () tsk.func (tsk.parm0 , Tsk.parm1, Tsk.parm2) class Thrd_pool (object): Def __init__ (self, Thd_count, tl): Self.thds = [] for i in Range (Thd_count): Self.thds.append (THRD (TL)) def run (self): for THD in Self.thds:thd.start ()def func (Parm0=none, Parm1=none, parm2=none): print ' count:%s, thrd_name:%s '% (str (PARM0), Threading.currentthread (). GetName ()) def cleanup (Signo, stkframe): Print (' oops! Got signal%s ', Signo) os._exit (0) If __name__ = = ' __main__ ': signal.signal (signal. SIGINT, Cleanup) signal.signal (signal. Sigquit, Cleanup) signal.signal (signal. SIGTERM, cleanup) tl = task_list () TP = Thrd_pool (6, TL) tp.run () Count = 0 while true:ti = Task_info ( ) Ti.parm0 = Count Ti.func = Func tl.append (ti) Count + = 1 Time.sleep (2) Pass