Pythonのthreading
とモジュールの違いは何ですか?thread
5 に答える
Python 3では、thread
名前がに変更されました_thread
。を実装するために使用されるのはインフラストラクチャコードでthreading
あり、通常のPythonコードはその近くに配置されるべきではありません。
_thread
基盤となるOSレベルのプロセスのかなり生のビューを公開します。これはほとんどあなたが望むものではないので、Py3kで名前を変更して、それが実際には単なる実装の詳細であることを示します。
threading
いくつかの追加の自動アカウンティングといくつかの便利なユーティリティが追加され、これらすべてが標準のPythonコードの推奨オプションになります。
threading
は、インターフェースとなる高レベルのモジュールにすぎませんthread
。
threading
ドキュメントについては、こちらを参照してください。
私が間違っていなければ、関数を別のスレッドとしてthread
実行できますが、クラスを作成する必要がありますが、より多くの機能を取得できます。threading
編集:これは正確には正しくありません。threading
モジュールは、スレッドを作成するさまざまな方法を提供します。
threading.Thread(target=function_name).start()
threading.Thread
独自のrun()
メソッドを使用しての子クラスを作成し、開始します
Python には、スレッド化に使用でき、完全に機能するライブラリがもう 1 つあります。
parallel.futures というライブラリ。これにより、作業が容易になります。
これには、スレッド プーリングとプロセス プーリングがあります。
以下から洞察が得られます。
ThreadPoolExecutor の例
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout=timeout) as conn:
return conn.read()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
もう一つの例
import concurrent.futures
import math
PRIMES = [
112272535095293,
112582705942171,
112272535095293,
115280095190773,
115797848077099,
1099726899285419]
def is_prime(n):
if n % 2 == 0:
return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0:
return False
return True
def main():
with concurrent.futures.ThreadPoolExecutor() as executor:
for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
print('%d is prime: %s' % (number, prime))
if __name__ == '__main__':
main()
モジュール "Thread" はスレッドを関数として扱いますが、モジュール "threading" はオブジェクト指向の方法で実装されます。つまり、すべてのスレッドがオブジェクトに対応します。