I realize I could use the Pool class and probably get what I needed, but I want a little finer control over my problem. I have more jobs than I do processors, so I don't want them to run all at one time.
For instance:
from multiprocessing import Process,cpu_count
for dir_name in directories:
src_dir = os.path.join(top_level,dir_name)
dst_dir = src_dir.replace(args.src_dir,args.target_dir)
p = Process(target=transfer_directory, args=(src_dir, dst_dir,))
p.start()
However, if I have more than 16 directories, I then will start more jobs than I have processors. Here was my solution that is really hack.
from multiprocessing import Process,cpu_count
jobs = []
for dir_name in directories:
src_dir = os.path.join(top_level,dir_name)
dst_dir = src_dir.replace(args.src_dir,args.target_dir)
p = Process(target=transfer_directory, args=(src_dir, dst_dir,))
jobs.append(p)
alive_jobs = []
while jobs:
if len(alive_jobs) >= cpu_count():
time.sleep(5)
print alive_jobs
for aj in alive_jobs:
if aj.is_alive():
continue
else:
print "job {} removed".format(aj)
alive_jobs.remove(aj)
continue
for job in jobs:
if job.is_alive():
continue
job.start()
alive_jobs.append(job)
print alive_jobs
jobs.remove(job)
if len(alive_jobs) >= cpu_count():
break
Is there a better solution using the built in tools?