Python の concurrent future モジュールの概要 (コード)
この記事では、Python の concurrent future モジュールについての紹介 (コード) を紹介します。一定の参考値があります。必要な友人は参照してください。お役に立てれば幸いです。
concurrent.futures モジュール
このモジュールの主な機能は、ThreadPoolExecutor クラスと ProcessPoolExecutor クラスです。どちらのクラスも concurrent.futures._base.Executor クラスを継承しています。それらが実装するインターフェイスは使用できます。さまざまな Callable オブジェクトはスレッドまたはプロセスで実行され、それらはすべて内部的にワーカー スレッドまたはプロセス プールを維持します。
ThreadPoolExecutor クラスと ProcessPoolExecutor クラスは高度なクラスであり、ほとんどの場合、実装の詳細に注意を払うことなく、使い方を学ぶだけで十分です。
#ProcessPoolExecutor クラス>class ThreadPoolExecutor(concurrent.futures._base.Executor) >| This is an abstract base class for concrete asynchronous executors. >| Method resolution order: >| ThreadPoolExecutor | concurrent.futures._base.Executor | builtins.object | | Methods defined here: | | init(self, max_workers=None, thread_name_prefix='') | Initializes a new ThreadPoolExecutor instance. | | Args: | max_workers: The maximum number of threads that can be used to | execute the given calls. | thread_name_prefix: An optional name prefix to give our threads. | | shutdown(self, wait=True) | Clean-up the resources associated with the Executor. | | It is safe to call this method several times. Otherwise, no other | methods can be called after this one. | | Args: | wait: If True then shutdown will not return until all running | futures have finished executing and the resources used by the | executor have been reclaimed. | | submit(self, fn, *args, **kwargs) | Submits a callable to be executed with the given arguments. | | Schedules the callable to be executed as fn(*args, **kwargs) and returns | a Future instance representing the execution of the callable. | | Returns: | A Future representing the given call. | | ---------------------------------------------------------------------- | Methods inherited from concurrent.futures._base.Executor: | | enter(self) | | exit(self, exc_type, exc_val, exc_tb) | | map(self, fn, *iterables, timeout=None, chunksize=1) | Returns an iterator equivalent to map(fn, iter). | | Args: | fn: A callable that will take as many arguments as there are | passed iterables. | timeout: The maximum number of seconds to wait. If None, then there | is no limit on the wait time. | chunksize: The size of the chunks the iterable will be broken into | before being passed to a child process. This argument is only | used by ProcessPoolExecutor; it is ignored by | ThreadPoolExecutor. | | Returns: | An iterator equivalent to: map(func, *iterables) but the calls may | be evaluated out-of-order. | | Raises: | TimeoutError: If the entire result iterator could not be generated | before the given timeout. | Exception: If fn(*args) raises for any values.
- map() メソッド。メソッドmap()、つまりマッピング内で、パラメータは次のとおりです:
- 呼び出し可能な関数 fn
- イテレータ iterables
- タイムアウト期間 timeout
- チャンク数 chunksize が 1 より大きい場合、イテレータはチャンクで処理されます
- shutdown() メソッドは、現在のエグゼキュータ (エグゼキュータ) に関連するすべてのリソースをクリーンアップします。
- submit() メソッドは、呼び出し可能なオブジェクトは fn
- concurrent.futures._base.Executor から __enter__() メソッドと __exit__() メソッドを継承します。これは、ProcessPoolExecutor オブジェクトを with ステートメントで使用できることを意味します。
from concurrent import futures
with futures.ProcessPoolExecutor(max_works=3) as executor:
executor.map()
ログイン後にコピー
ThreadPoolExecutor クラス
from concurrent import futures with futures.ProcessPoolExecutor(max_works=3) as executor: executor.map()
class ThreadPoolExecutor(concurrent.futures._base.Executor) | This is an abstract base class for concrete asynchronous executors. | | Method resolution order: | ThreadPoolExecutor | concurrent.futures._base.Executor | builtins.object | | Methods defined here: | | init(self, max_workers=None, thread_name_prefix='') | Initializes a new ThreadPoolExecutor instance. | | Args: | max_workers: The maximum number of threads that can be used to | execute the given calls. | thread_name_prefix: An optional name prefix to give our threads. | | shutdown(self, wait=True) | Clean-up the resources associated with the Executor. | | It is safe to call this method several times. Otherwise, no other | methods can be called after this one. | | Args: | wait: If True then shutdown will not return until all running | futures have finished executing and the resources used by the | executor have been reclaimed. | | submit(self, fn, *args, **kwargs) | Submits a callable to be executed with the given arguments. | | Schedules the callable to be executed as fn(*args, **kwargs) and returns | a Future instance representing the execution of the callable. | | Returns: | A Future representing the given call. | | ---------------------------------------------------------------------- | Methods inherited from concurrent.futures._base.Executor: | | enter(self) | | exit(self, exc_type, exc_val, exc_tb) | | map(self, fn, *iterables, timeout=None, chunksize=1) | Returns an iterator equivalent to map(fn, iter). | | Args: | fn: A callable that will take as many arguments as there are | passed iterables. | timeout: The maximum number of seconds to wait. If None, then there | is no limit on the wait time. | chunksize: The size of the chunks the iterable will be broken into | before being passed to a child process. This argument is only | used by ProcessPoolExecutor; it is ignored by | ThreadPoolExecutor. | | Returns: | An iterator equivalent to: map(func, *iterables) but the calls may | be evaluated out-of-order. | | Raises: | TimeoutError: If the entire result iterator could not be generated | before the given timeout. | Exception: If fn(*args) raises for any values.
from time import sleep, strftime from concurrent import futures def display(*args): print(strftime('[%H:%M:%S]'), end="") print(*args) def loiter(n): msg = '{}loiter({}): doing nothing for {}s' display(msg.format('\t'*n, n, n)) sleep(n) msg = '{}loiter({}): done.' display(msg.format('\t'*n, n)) return n*10 def main(): display('Script starting') executor = futures.ThreadPoolExecutor(max_workers=3) results = executor.map(loiter, range(5)) display('results:', results) display('Waiting for inpidual results:') for i, result in enumerate(results): display('result {} : {}'.format(i, result)) if __name__ == '__main__': main()
[20:32:12]Script starting [20:32:12]loiter(0): doing nothing for 0s [20:32:12]loiter(0): done. [20:32:12] loiter(1): doing nothing for 1s [20:32:12] loiter(2): doing nothing for 2s [20:32:12]results: <generator object Executor.map.<locals>.result_iterator at 0x00000246DB21BC50> [20:32:12]Waiting for inpidual results: [20:32:12] loiter(3): doing nothing for 3s [20:32:12]result 0 : 0 [20:32:13] loiter(1): done. [20:32:13] loiter(4): doing nothing for 4s [20:32:13]result 1 : 10 [20:32:14] loiter(2): done. [20:32:14]result 2 : 20 [20:32:15] loiter(3): done. [20:32:15]result 3 : 30 [20:32:17] loiter(4): done. [20:32:17]result 4 : 40
Python がフューチャーを通じて同時実行性の問題を処理する方法の詳細な例
以上がPython の concurrent future モジュールの概要 (コード)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









PHPとPythonには独自の利点と短所があり、選択はプロジェクトのニーズと個人的な好みに依存します。 1.PHPは、大規模なWebアプリケーションの迅速な開発とメンテナンスに適しています。 2。Pythonは、データサイエンスと機械学習の分野を支配しています。

PythonとJavaScriptには、コミュニティ、ライブラリ、リソースの観点から、独自の利点と短所があります。 1)Pythonコミュニティはフレンドリーで初心者に適していますが、フロントエンドの開発リソースはJavaScriptほど豊富ではありません。 2)Pythonはデータサイエンスおよび機械学習ライブラリで強力ですが、JavaScriptはフロントエンド開発ライブラリとフレームワークで優れています。 3)どちらも豊富な学習リソースを持っていますが、Pythonは公式文書から始めるのに適していますが、JavaScriptはMDNWebDocsにより優れています。選択は、プロジェクトのニーズと個人的な関心に基づいている必要があります。

DockerはLinuxカーネル機能を使用して、効率的で孤立したアプリケーションランニング環境を提供します。その作業原則は次のとおりです。1。ミラーは、アプリケーションを実行するために必要なすべてを含む読み取り専用テンプレートとして使用されます。 2。ユニオンファイルシステム(UnionFS)は、違いを保存するだけで、スペースを節約し、高速化する複数のファイルシステムをスタックします。 3.デーモンはミラーとコンテナを管理し、クライアントはそれらをインタラクションに使用します。 4。名前空間とcgroupsは、コンテナの分離とリソースの制限を実装します。 5.複数のネットワークモードは、コンテナの相互接続をサポートします。これらのコア概念を理解することによってのみ、Dockerをよりよく利用できます。

PytorchをCentosシステムにインストールする場合、適切なバージョンを慎重に選択し、次の重要な要因を検討する必要があります。1。システム環境互換性:オペレーティングシステム:Centos7以上を使用することをお勧めします。 Cuda and Cudnn:PytorchバージョンとCudaバージョンは密接に関連しています。たとえば、pytorch1.9.0にはcuda11.1が必要ですが、pytorch2.0.1にはcuda11.3が必要です。 CUDNNバージョンは、CUDAバージョンとも一致する必要があります。 Pytorchバージョンを選択する前に、互換性のあるCUDAおよびCUDNNバージョンがインストールされていることを確認してください。 Pythonバージョン:Pytorch公式支店

VSコードでは、次の手順を通じて端末でプログラムを実行できます。コードを準備し、統合端子を開き、コードディレクトリが端末作業ディレクトリと一致していることを確認します。プログラミング言語(pythonのpython your_file_name.pyなど)に従って実行コマンドを選択して、それが正常に実行されるかどうかを確認し、エラーを解決します。デバッガーを使用して、デバッグ効率を向上させます。

Pythonは、自動化、スクリプト、およびタスク管理に優れています。 1)自動化:OSやShutilなどの標準ライブラリを介してファイルバックアップが実現されます。 2)スクリプトの書き込み:Psutilライブラリを使用してシステムリソースを監視します。 3)タスク管理:スケジュールライブラリを使用してタスクをスケジュールします。 Pythonの使いやすさと豊富なライブラリサポートにより、これらの分野で優先ツールになります。

VSコード拡張機能は、悪意のあるコードの隠れ、脆弱性の活用、合法的な拡張機能としての自慰行為など、悪意のあるリスクを引き起こします。悪意のある拡張機能を識別する方法には、パブリッシャーのチェック、コメントの読み取り、コードのチェック、およびインストールに注意してください。セキュリティ対策には、セキュリティ認識、良好な習慣、定期的な更新、ウイルス対策ソフトウェアも含まれます。

NGINXのインストールをインストールするには、次の手順に従う必要があります。開発ツール、PCRE-Devel、OpenSSL-Develなどの依存関係のインストール。 nginxソースコードパッケージをダウンロードし、それを解凍してコンパイルしてインストールし、/usr/local/nginxとしてインストールパスを指定します。 nginxユーザーとユーザーグループを作成し、アクセス許可を設定します。構成ファイルnginx.confを変更し、リスニングポートとドメイン名/IPアドレスを構成します。 nginxサービスを開始します。依存関係の問題、ポート競合、構成ファイルエラーなど、一般的なエラーに注意する必要があります。パフォーマンスの最適化は、キャッシュをオンにしたり、ワーカープロセスの数を調整するなど、特定の状況に応じて調整する必要があります。
