<s> import collections <EOL> import threading <EOL> import functools <EOL> def foreach ( source , action , n_jobs = <NUM_LIT:0> ) : <EOL> """<STR_LIT>""" <EOL> if not n_jobs : <EOL> _foreach_no_limit ( source , action ) <EOL> elif n_jobs == <NUM_LIT:1> : <EOL> for item in source : <EOL> action ( item ) <EOL> else : <EOL> _foreach_with_limit ( source , action , n_jobs ) <EOL> def _foreach_worker ( q , action ) : <EOL> while True : <EOL> try : <EOL> item = q . popleft ( ) <EOL> except IndexError : <EOL> break <EOL> action ( item ) <EOL> def _foreach_with_limit ( source , action , n_jobs ) : <EOL> assert n_jobs >= <NUM_LIT:0> <EOL> q = collections . deque ( ) <EOL> for item in source : <EOL> q . append ( item ) <EOL> threads = [ threading . Thread ( target = functools . partial ( _foreach_worker , q , action ) ) <EOL> for _ in range ( n_jobs ) ] <EOL> for t in threads : <EOL> t . start ( ) <EOL> for t in threads : <EOL> t . join ( ) <EOL> def _foreach_no_limit ( source , action ) : <EOL> threads = [ threading . Thread ( target = functools . partial ( action , item ) ) <EOL> for item in source ] <EOL> for t in threads : <EOL> t . start ( ) <EOL> for t in threads : <EOL> t . join ( ) </s>
