As a follow up on this question, I have a trivial script which starts a threadpoolexecutor
to read in a json
file. While doing that I want to it count from 1 to 9 using a for
loop. For some reason even though I used executor.shutdown(wait=False)
it still blocks and waits for the read_employees
method to execute.
According to the documentation:
If wait is False then this method will return immediately and the resources associated with the executor will be freed when all pending futures are done executing
import concurrent.futures
import json
import time
def read_employees(read_file):
with open(read_file) as f_obj:
employees = json.load(f_obj)
for emp in employees:
print(emp)
time.sleep(3)
def start_thread():
filename = 'employee.json'
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.submit(read_employees, filename)
executor.shutdown(wait=False)
def print_number():
for num in range(1,10):
time.sleep(2)
print(num)
start_thread()
print_number()
If I were to do this:
def read_employees(read_file):
with open(read_file) as f_obj:
employees = json.load(f_obj)
for emp in employees:
time.sleep(5)
print(emp)
def print_number():
for num in range(1,10):
print(num)
filename = 'employee.json'
empThread = threading.Thread(target=read_employees, args=(filename,))
empThread.start()
print_number()
It counts from 1 to 9 first and then prints out the employees, the delay is because of sleep while reading the employees. Like so:
1
2
3
4
5
6
7
8
9
ams@yourcompanyname.com
bcs@yourcompanyname.com
How do I achieve the same output using the threadpoolexecutor
without blocking?