python多进程使用及线程池的使用方法代码详解
多进程:主要运行multiprocessing模块
importos,time
importsys
frommultiprocessingimportProcess
classMyProcess(Process):
"""docstringforMyProcess"""
def__init__(self,arg,callback):
super(MyProcess,self).__init__()
self.arg=arg
self.callback=callback
defrun(self):
self.callback(self.arg)
deftest(arg):
print("子进程{}开始>>>pid={}".format(arg,os.getpid()))
foriinrange(1,5):
sys.stdout.write("子进程{}运行中{}\r".format(arg,i))
sys.stdout.flush()
time.sleep(1)
defmain():
print("主进程开始>>>pid={}".format(os.getpid()))
myp=MyProcess(1,test)
myp.start()
myp2=MyProcess(2,test)
myp2.start()
myp.join()
myp2.join()
print("主进程终止")
if__name__=='__main__':
main()
线程池:主要运用了未来模块!下面例子,第一个是正常,第二第线程池,第三个用运行了2个线程池,会排队
fromconcurrent.futuresimportThreadPoolExecutor
importtime
defsayhello(a):
print("hello:"+a)
time.sleep(2)
defmain():
seed=["a","b","c"]
start1=time.time()
foreachinseed:
sayhello(each)
end1=time.time()
print("time1:"+str(end1-start1))
start2=time.time()
withThreadPoolExecutor(3)asexecutor:
foreachinseed:
executor.submit(sayhello,each)
end2=time.time()
print("time2:"+str(end2-start2))
start3=time.time()
withThreadPoolExecutor(2)asexecutor1:
executor1.map(sayhello,seed)
end3=time.time()
print("time3:"+str(end3-start3))
if__name__=='__main__':
main()
总结
以上所述是小编给大家介绍的python多进程使用及线程池的使用方法代码详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!