2019-08-18 22:11:05 +00:00
|
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
from functools import partial
|
2020-10-07 22:46:13 +00:00
|
|
|
from multiprocessing import Pool, RLock, freeze_support
|
|
|
|
from random import random
|
|
|
|
from threading import RLock as TRLock
|
|
|
|
from time import sleep
|
2017-09-21 00:54:51 +00:00
|
|
|
|
2020-10-07 22:46:13 +00:00
|
|
|
from tqdm.auto import tqdm, trange
|
|
|
|
from tqdm.contrib.concurrent import process_map, thread_map
|
|
|
|
|
2019-10-31 16:31:18 +00:00
|
|
|
NUM_SUBITERS = 9
|
2017-09-21 00:54:51 +00:00
|
|
|
|
|
|
|
|
2020-12-18 22:55:41 +00:00
|
|
|
def progresser(n, auto_position=True, write_safe=False, blocking=True, progress=False):
|
2021-02-17 16:03:15 +00:00
|
|
|
interval = random() * 0.002 / (NUM_SUBITERS - n + 2) # nosec
|
2017-09-21 00:54:51 +00:00
|
|
|
total = 5000
|
2023-03-03 16:32:58 +00:00
|
|
|
text = f"#{n}, est. {interval * total:<04.2g}s"
|
2020-01-24 22:28:22 +00:00
|
|
|
for _ in trange(total, desc=text, disable=not progress,
|
2019-11-08 23:53:58 +00:00
|
|
|
lock_args=None if blocking else (False,),
|
2019-10-31 19:31:53 +00:00
|
|
|
position=None if auto_position else n):
|
2017-09-21 00:54:51 +00:00
|
|
|
sleep(interval)
|
2019-08-18 22:11:05 +00:00
|
|
|
# NB: may not clear instances with higher `position` upon completion
|
|
|
|
# since this worker may not know about other bars #796
|
2023-08-09 17:37:21 +00:00
|
|
|
if write_safe: # we think we know about other bars
|
2019-08-18 22:11:05 +00:00
|
|
|
if n == 6:
|
|
|
|
tqdm.write("n == 6 completed")
|
2020-01-24 22:28:22 +00:00
|
|
|
return n + 1
|
2019-08-18 22:11:05 +00:00
|
|
|
|
2017-09-21 00:54:51 +00:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
freeze_support() # for Windows support
|
2019-10-31 16:31:18 +00:00
|
|
|
L = list(range(NUM_SUBITERS))[::-1]
|
|
|
|
|
2020-01-24 22:28:22 +00:00
|
|
|
print("Simple thread mapping")
|
2023-03-03 15:43:42 +00:00
|
|
|
thread_map(partial(progresser, write_safe=True), L, max_workers=4)
|
2020-01-24 22:28:22 +00:00
|
|
|
|
|
|
|
print("Simple process mapping")
|
|
|
|
process_map(partial(progresser), L, max_workers=4)
|
|
|
|
|
2019-10-31 16:31:18 +00:00
|
|
|
print("Manual nesting")
|
|
|
|
for i in trange(16, desc="1"):
|
|
|
|
for _ in trange(16, desc="2 @ %d" % i, leave=i % 2):
|
|
|
|
sleep(0.01)
|
|
|
|
|
2019-08-18 22:11:05 +00:00
|
|
|
print("Multi-processing")
|
2020-10-07 22:46:13 +00:00
|
|
|
tqdm.set_lock(RLock())
|
2019-10-31 16:31:18 +00:00
|
|
|
p = Pool(initializer=tqdm.set_lock, initargs=(tqdm.get_lock(),))
|
2020-01-24 22:28:22 +00:00
|
|
|
p.map(partial(progresser, progress=True), L)
|
2017-09-21 00:54:51 +00:00
|
|
|
|
2020-10-07 22:46:13 +00:00
|
|
|
print("Multi-threading")
|
|
|
|
tqdm.set_lock(TRLock())
|
2023-03-03 15:43:42 +00:00
|
|
|
with ThreadPoolExecutor(initializer=tqdm.set_lock, initargs=(tqdm.get_lock(),)) as p:
|
|
|
|
p.map(partial(progresser, progress=True, write_safe=True, blocking=False), L)
|