5

違いがわかりません。この違いを見るのを手伝ってください。そして、ProcessPoolExecutor はどうですか? 彼の動作は同じですか?

def func(task):
    do_something(task)

tasks = [task for i in range(12)]
executor = ThreadPoolExecutor(4)
executor.map(func, tasks)
executor.shutdown(wait=True)  # ok, here the main thread waits for others

tasks = [task for i in range(12)]
executor = ThreadPoolExecutor(4)
executor.map(func, tasks)
executor.shutdown(wait=False)  # here it doesn't wait and what can happens bad?

tasks = [task for i in range(12)]
executor = ThreadPoolExecutor(4)
executor.map(func, tasks)  # if i don't call shutdown ?
4

1 に答える 1

6

ドキュメントから:

wait が True の場合、保留中のすべての Future の実行が完了し、executor に関連付けられたリソースが解放されるまで、このメソッドは返されません。wait が False の場合、このメソッドはすぐに戻り、保留中のすべての Future の実行が完了すると、executor に関連付けられたリソースが解放されます。wait の値に関係なく、保留中のすべての Future の実行が完了するまで、Python プログラム全体は終了しません。

これは最初の 2 つの例をカバーしています。

3 つ目はThreadPoolExecutor、「コンテキスト マネージャー」プロトコルに準拠しているため、実行がブロックを終了するとすぐにメソッドが自動的に呼び出されるwithようにするために、ステートメントに沿って使用できます。shutdownwith

デフォルトはTrue、パラメータを省略した場合、またはコンテキストマネージャとして使用した場合です。withブロック内で使用しても、 の値に関係なく役に立ちませんwait

[編集]

コードを編集しました。plsを参照してください、私の最後の質問があります

shutdownすべてのリソースを明示的に解放し、新しい呼び出しが成功しsubmitないようにする場合にのみ、メソッドを呼び出します。mapshutdown を呼び出さない (またはThreadPoolExecutorコンテキスト マネージャーとして使用しない) 場合、リソースは Python プログラム全体が終了したときにのみ解放されます (保留中のすべての Future が完了するまで終了しません)。

コンテキスト マネージャーを呼び出したり、コンテキスト マネージャーとして使用shutdownしたりすると、保留中のすべてのフューチャーの実行が完了するまでブロックされます。wait==TrueThreadPoolExecutor

shutdown明示的に呼び出すために私が考えることができる唯一のユースケースは次のとおりです。

executor = ThreadPoolExecutor(4)
try:
    executor.map(func, tasks)
finally:
    executor.shutdown(wait=False)

コンテキストを提供するために、これはこの質問の最初のバージョンのコード スニペットです。

def func(task):
    do_something(task)

tasks = [task for i in range(12)]
with ThreadPoolExecutor(4) as executor:
    executor.map(func, tasks)
    executor.shutdown(wait=True)  # what is happening here?

tasks = [task for i in range(12)]
with ThreadPoolExecutor(4) as executor:
    executor.map(func, tasks)
    executor.shutdown(wait=False)  # what is happening here?

tasks = [task for i in range(12)]
with ThreadPoolExecutor(4) as executor:
    executor.map(func, tasks)  # and without shutdown()?

冗長であることに注意してください-同様tasks = [task for i in range(12)]に使用できます。executor.map(func, range(12))

于 2015-02-09T19:20:42.370 に答える