82

Pythonのthreadingとモジュールの違いは何ですか?thread

4

5 に答える 5

103

Python 3では、thread名前がに変更されました_thread。を実装するために使用されるのはインフラストラクチャコードでthreadingあり、通常のPythonコードはその近くに配置されるべきではありません。

_thread基盤となるOSレベルのプロセスのかなり生のビューを公開します。これはほとんどあなたが望むものではないので、Py3kで名前を変更して、それが実際には単なる実装の詳細であることを示します。

threadingいくつかの追加の自動アカウンティングといくつかの便利なユーティリティが追加され、これらすべてが標準のPythonコードの推奨オプションになります。

于 2011-04-07T08:30:24.220 に答える
37

threadingは、インターフェースとなる高レベルのモジュールにすぎませんthread

threadingドキュメントについては、こちらを参照してください。

http://docs.python.org/library/threading.html

于 2011-04-06T15:03:42.033 に答える
11

私が間違っていなければ、関数を別のスレッドとしてthread実行できますが、クラス作成する必要がありますが、より多くの機能を取得できます。threading

編集:これは正確には正しくありません。threadingモジュールは、スレッドを作成するさまざまな方法を提供します。

  • threading.Thread(target=function_name).start()
  • threading.Thread独自のrun()メソッドを使用しての子クラスを作成し、開始します
于 2011-04-06T15:22:46.770 に答える
-1

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()
于 2019-03-26T11:14:55.470 に答える
-2

モジュール "Thread" はスレッドを関数として扱いますが、モジュール "threading" はオブジェクト指向の方法で実装されます。つまり、すべてのスレッドがオブジェクトに対応します。

于 2015-06-07T03:38:51.463 に答える