Python - Threadpoolexecutor Blocking. How To Unblock
The following code is blocking: import threading from concurrent.futures import ThreadPoolExecutor import os from pprint import pprint import time def sleep(seconds): for i i
Solution 1:
You don't get expected output a handful of threads would have output at once
because you don't start a handful of threads
. You create only one thread at a time to perform a single task which is a call of get_instance()
function.
You may get something close to the desired output with following code:
import datetime as dt
from concurrent.futures import ThreadPoolExecutor
import os
import threading
import time
defhandle_instance(h):
t = dt.datetime.time(dt.datetime.now())
print('[{}] Got instance {}'.format(t, h))
print('[{}] Result is {}'.format(t, h.result()))
print(id(t))
deftask():
print("Executing our Task on Process: {}".format(os.getpid()))
time.sleep(3)
return1defmain():
with ThreadPoolExecutor(3) as th_exec:
for dummy inrange(3):
th_future = th_exec.submit(task)
th_future.add_done_callback(handle_instance)
if __name__ == "__main__":
try:
whileTrue:
print('A new cycle of execution just started...')
threading.Thread(target=main, daemon=True).start()
time.sleep(5)
except KeyboardInterrupt:
raise SystemExit('\nexit by user')
Output:
A new cycle of execution just started...
Executing our Task on Process: 2528
Executing our Task on Process: 2528
Executing our Task on Process: 2528
[10:40:19.100711] Got instance <Future at 0x262342a9320 state=finished returned int>
[10:40:19.100711] Got instance <Future at 0x2623425e128 state=finished returned int>
[10:40:19.100711] Result is1
[10:40:19.100711] Result is1
[10:40:19.100711] Got instance <Future at 0x26233fe3ef0 state=finished returned int>
[10:40:19.100711] Result is1
exit by user
Post a Comment for "Python - Threadpoolexecutor Blocking. How To Unblock"