python多进程学习笔记
# coding=utf-8 from multiprocessing import Process,Pool import os import time def printf(args): # time.sleep(1) print "pool: %d [%s]---%s" % (args+1,os.getpid(),time.time()) # os.getpid()获取当前的进程的ID def works(func, lista, worknum): t_start = time.time() # 开始计时 pool = Pool(worknum) # 定义并发进程数,worknum如果给了5,就是5个进程并发,如果要处理下面100次func函数的任务,那么并发后只需要处理20次 for i in lista: # 相当于要执行的任务量(range(100)) pool.apply_async(func,args=(i,)) # 执行func函数(即printf函数) pool.close() pool.join() # 调用join函数前,先调用close函数。执行完close后,不会有新的进程加入到pool,join函数等待所以子进程结束 t_end = time.time() # 计时结束 t = t_end - t_start print "the program time is :%s" %t if __name__ == "__main__": lista = range(100) procs = 10 works(printf, lista, procs)