<s> try : <EOL> import sys <EOL> import inspect <EOL> from Queue import Queue <EOL> from threading import Thread <EOL> except ImportError , err : <EOL> import sys <EOL> sys . stderr . write ( "<STR_LIT>" % ( err , __file__ , inspect . currentframe ( ) . f_lineno ) ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> class Worker ( Thread ) : <EOL> def __init__ ( self , tasks ) : <EOL> Thread . __init__ ( self ) <EOL> self . tasks = tasks <EOL> self . daemon = True <EOL> self . start ( ) <EOL> def run ( self ) : <EOL> while True : <EOL> func , args , kargs = self . tasks . get ( True , None ) <EOL> if not func : <EOL> break <EOL> try : <EOL> func ( * args , ** kargs ) <EOL> except Exception , err : <EOL> print err <EOL> pass <EOL> self . tasks . task_done ( ) <EOL> class ThreadPool : <EOL> def __init__ ( self , num_threads ) : <EOL> self . threads = [ ] <EOL> self . num_threads = num_threads <EOL> self . tasks = Queue ( self . num_threads ) <EOL> for _ in range ( self . num_threads ) : <EOL> worker = Worker ( self . tasks ) <EOL> self . threads . append ( worker ) <EOL> def add_task ( self , func , * args , ** kargs ) : <EOL> self . tasks . put ( ( func , args , kargs ) ) <EOL> def wait_completion ( self ) : <EOL> self . tasks . join ( ) <EOL> for _ in range ( self . num_threads ) : <EOL> self . add_task ( None , None , None ) <EOL> for t in self . threads : <EOL> t . join ( ) </s>
