Python的多线程是假的,但是多进程是真的。在处理计算需求比较大的问题时可以考虑使用多进程:
#coding=utf-8
import copy
import numpy as np
import multiprocessing
import z_facility as fac
from multiprocessing import Pool
# 输入处理的一个单元,比如list的一个元素
def func(line):
# 全局记录完成进度
done_num.value += 1
if done_num.value%1000 == 0:
print done_num.value/1000, '% done'
return res_line
# 输入一个单元的处理结果,将其写入文件保存(a+模式)
def bk(res_line):
with open('res_file', 'a+') as g:
g.writelines(cp_line)
if __name__=='__main__':
f = open('target_file', 'r')
lines = f.readlines()
f.close()
# 全局变量,记录完成进度
done_num = multiprocessing.Value("d", 0)
p = Pool(4) # 进程数量:4
# 调用多进程处理lines,处理的结果用bk
p.map_async(func, lines, callback=bk)
p.close()
p.join()