Python implements thread pool code sharing

Source: Internet
Author: User
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
  • 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.