2014-05-01 07:30:01 +00:00
|
|
|
import time
|
2014-05-01 07:13:03 +00:00
|
|
|
from multiprocessing import Pool
|
|
|
|
|
2021-05-27 05:50:04 +00:00
|
|
|
|
2014-05-01 07:13:03 +00:00
|
|
|
def f(x):
|
2021-05-27 05:50:04 +00:00
|
|
|
return x * x
|
|
|
|
|
2014-05-01 07:13:03 +00:00
|
|
|
|
|
|
|
pool = Pool(4)
|
|
|
|
future = pool.apply_async(f, (10,))
|
2017-09-03 08:10:56 +00:00
|
|
|
assert future.get() == 100
|
2014-05-01 07:30:01 +00:00
|
|
|
|
2021-05-27 05:50:04 +00:00
|
|
|
|
2014-05-01 07:30:01 +00:00
|
|
|
def f2(x):
|
2017-09-03 08:10:56 +00:00
|
|
|
time.sleep(0.5)
|
2014-05-01 07:30:01 +00:00
|
|
|
return x + 1
|
|
|
|
|
2021-05-27 05:50:04 +00:00
|
|
|
|
2014-05-01 07:30:01 +00:00
|
|
|
future = pool.apply_async(f2, (10,))
|
2017-09-03 08:10:56 +00:00
|
|
|
iter = 0
|
2014-05-01 07:30:01 +00:00
|
|
|
while not future.ready():
|
2021-05-27 05:50:04 +00:00
|
|
|
# print("not ready")
|
2017-09-03 08:10:56 +00:00
|
|
|
time.sleep(0.1)
|
|
|
|
iter += 1
|
2014-05-01 07:44:22 +00:00
|
|
|
|
2017-09-03 08:10:56 +00:00
|
|
|
assert future.get() == 11
|
|
|
|
assert iter >= 5 and iter <= 8
|
2014-05-01 07:44:22 +00:00
|
|
|
|
|
|
|
t = time.time()
|
|
|
|
futs = [
|
|
|
|
pool.apply_async(f2, (10,)),
|
|
|
|
pool.apply_async(f2, (11,)),
|
|
|
|
pool.apply_async(f2, (12,)),
|
|
|
|
]
|
|
|
|
|
2017-09-03 08:10:56 +00:00
|
|
|
iter = 0
|
2014-05-01 07:44:22 +00:00
|
|
|
while True:
|
2021-05-27 05:50:04 +00:00
|
|
|
# not all(futs):
|
2014-05-01 07:44:22 +00:00
|
|
|
c = 0
|
|
|
|
for f in futs:
|
|
|
|
if not f.ready():
|
|
|
|
c += 1
|
|
|
|
if not c:
|
|
|
|
break
|
2021-05-27 05:50:04 +00:00
|
|
|
# print("not ready2")
|
2017-09-03 08:10:56 +00:00
|
|
|
time.sleep(0.1)
|
|
|
|
iter += 1
|
|
|
|
|
|
|
|
assert iter >= 5 and iter <= 8
|
2014-05-01 07:44:22 +00:00
|
|
|
|
|
|
|
print("Run 3 parallel sleep(1)'s in: ", time.time() - t)
|