this question의 후속 조치로, json
파일을 읽으려면 threadpoolexecutor
을 시작하는 간단한 스크립트가 있습니다. 루프를 사용하여 1에서 9까지 카운트하고 싶다면 for
루프를 사용하십시오. 어떤 이유로 비록 내가 executor.shutdown(wait=False)
을 사용했지만 여전히 블록을 수행하고 read_employees
메쏘드가 실행되기를 기다린다.블로킹없이 ThreadPoolExecutor 사용
에 따르면 documentation :
대기는,이 메소드는 즉시 반환하고 대기중인 모든 선물이
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()
실행 완료되면 집행자와 관련된 자원이 해제됩니다 False이면
내가 이렇게하면 :
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()
먼저 1에서 9까지 계산 한 다음 직원을 인쇄합니다. 지연은 직원을 읽는 동안 수면으로 인한 것입니다. 그래서 같이 :
1
2
3
4
5
6
7
8
9
[email protected]
[email protected]
어떻게 차단하지 않고 threadpoolexecutor
를 사용하여 동일한 출력을 얻을 수 있습니까?
이것은이지만 막고 것처럼 여전히 출력 :
두 번째 옵션은 같은 것을 할 것입니다. –