优化之前的代码:
from multiprocessing.dummy import Pool as ThreadPool
from datetime import datetime
import time
def geEntry(a,b):
time.sleep(2)
now = datetime.now()
print(now)
return now
pool = ThreadPool(8)
now = datetime.now()
a=list(range(10))
print(a)
# entries=pool.map(self.geEntry, plan_obj.entries)
entries=[]
b=1
c=2
for i in a:
result=pool.apply_async(geEntry, args=(b,c))
entries.append(result.get())
pool.close()
pool.join()
Output:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2020-07-12 20:12:51.402016
2020-07-12 20:12:53.403585
2020-07-12 20:12:55.404262
2020-07-12 20:12:57.405886
2020-07-12 20:12:59.406552
2020-07-12 20:13:01.407239
2020-07-12 20:13:03.407955
2020-07-12 20:13:05.409428
2020-07-12 20:13:07.410663
2020-07-12 20:13:09.412293
优化后的代码:
from multiprocessing.dummy import Pool as ThreadPool
from datetime import datetime
import time
def geEntry(a,b):
time.sleep(2)
now = datetime.now()
print(now)
return now
pool = ThreadPool(8)
now = datetime.now()
a=list(range(10))
print(a)
# entries=pool.map(self.geEntry, plan_obj.entries)
entries=[]
b=1
c=2
for i in a:
result=pool.apply_async(geEntry, args=(b,c))
entries.append(result) #需要把result先放到list里,如果直接用result.get()会变成同步按顺序调用,多线程同时指向失效
pool.close()
pool.join()
for result in entries:
print("** %s" % result.get())
output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2020-07-12 20:06:57.046435
2020-07-12 20:06:57.046496
2020-07-12 20:06:57.046496
2020-07-12 20:06:57.046496
2020-07-12 20:06:57.046496
2020-07-12 20:06:57.046496
2020-07-12 20:06:57.046496
2020-07-12 20:06:57.046496
2020-07-12 20:06:59.047407
2020-07-12 20:06:59.047407
** 2020-07-12 20:06:57.046496
** 2020-07-12 20:06:57.046496
** 2020-07-12 20:06:57.046496
** 2020-07-12 20:06:57.046496
** 2020-07-12 20:06:57.046496
** 2020-07-12 20:06:57.046435
** 2020-07-12 20:06:57.046496
** 2020-07-12 20:06:57.046496
** 2020-07-12 20:06:59.047407
** 2020-07-12 20:06:59.047407