this questionのフォローアップとして、私はjson
ファイルで読むthreadpoolexecutor
を開始する簡単なスクリプトを持っています。それをやりながら、for
ループを使用して1から9までカウントします。私がexecutor.shutdown(wait=False)
を使用したにもかかわらず何らかの理由でそれはまだブロックし、read_employees
メソッドが実行されるのを待ちます。 documentationによるとBlockPoolExecutorをブロッキングなしで使用する
:
待ち時間がFalseの場合、このメソッドはすぐに返され、保留中のすべての先物が
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()
を実行して行われたときに、エグゼキュータに関連付けられたリソースが解放されます
私がこれを行う場合:
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
を使用して同じ出力を達成していますか?
私はは 'false'に' wait'を設定する理由ですが、それがブロックしているかのよう、それはまだ出力:
2番目のオプションは、このような何かを行うことです。 –