多线程

 1 import time
 2 import threading
 3 
 4 def f0():
 5     print(1)
 6 def f1():
 7     time.sleep(10)
 8     f0()
 9 
10 t= threading.Thread(target=f1)
11 t.setDaemon(True) # True:主线程不等待子线程执行,主线程结束,程序结束
12 t.start()
13 t= threading.Thread(target=f1)
14 t.setDaemon(True)
15 t.start()
16 t= threading.Thread(target=f1)
17 t.setDaemon(True)
18 t.start()

t.join() 主线程等待子线程执行,t.join(2)最多等待2秒

 进程池

p = Pool(5)

p.apply 每个任务是排队进行。进程.join() # 等待

p.apply_async 每一个任务都并发执行可设置回调函数,进程.无join();进程daemon=True  # 不等待

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 from multiprocessing import Pool
 4 import time
 5 
 6 def f1(a):
 7     time.sleep(2)
 8     print(a)
 9     return 100000000
10 
11 def f2(arg):
12     print(arg)
13 
14 if __name__ =='__main__':
15     p = Pool(5)
16     for i in range(10):
17         p.apply_async(func=f1,args=(i,),callback=f2)
18         print(11111111111111111111)
19     p.close()
20     #p.terminate()
21     p.join()
原文地址:https://www.cnblogs.com/Erick-L/p/6501057.html