Pythonスレッドの実装

参考記事

Pythonスレッドプールの使用法と実際の戦闘ThreadPoolExecutor

threading.Threadを作成します

threading.Thread構築方法:

threading.Thread(group=None, target=None, name=None,args=(), kwargs=None, *, daemon=None
  1. group:Noneにする必要があります。将来、ThreadGroupを拡張するときにクラス実装用に予約されています。
  2. ターゲット:呼び出される関数
  3. name:スレッド名。デフォルトはThread-1、Thread-2 ... Thread-Nです。
  4. args:関数の変数パラメーター
  5. kwargs:関数のキーワードパラメータ
  6. デーモン:デーモンプロセスであるかどうか、Trueはtrue、Falseはそうではありません
import random
import threading
import time


def doing(person, task):
    thread_name = threading.current_thread().name
    print("threadName=%s : %s start %s " % (thread_name, person, task))
    time.sleep(random.randrange(start=1, stop=5))
    print("threadName=%s : %s end %s " % (thread_name, person, task))


def test1():
    for i in range(0, 3):
        my_thread = threading.Thread(target=doing, args=("%d 号工人" % i, "%d 号任务" % i))
        my_thread.start()


if __name__ == "__main__":
    test1()

演算結果:

threadName=Thread-1 : 0 号工人 start 0 号任务 
threadName=Thread-2 : 1 号工人 start 1 号任务 
threadName=Thread-3 : 2 号工人 start 2 号任务 
threadName=Thread-2 : 1 号工人 end 1 号任务 
threadName=Thread-1 : 0 号工人 end 0 号任务 
threadName=Thread-3 : 2 号工人 end 2 号任务 

スレッドを継承します。スレッド

import random
import threading
import time

class DoingThread(threading.Thread):
    def __init__(self, person, task):
        super(DoingThread, self).__init__()
        self.person = person
        self.task = task

    def run(self):
        thread_name = threading.current_thread().name
        print("threadName=%s : %s start %s " % (thread_name, self.person, self.task))
        time.sleep(random.randrange(start=1, stop=5))
        print("threadName=%s : %s end %s " % (thread_name, self.person, self.task))


def test2():
    for i in range(0, 3):
        my_thread = DoingThread("%d 号工人" % i, "%d 号任务" % i)
        my_thread.start()


if __name__ == "__main__":
    test2()

演算結果:

threadName=Thread-1 : 0 号工人 start 0 号任务 
threadName=Thread-2 : 1 号工人 start 1 号任务 
threadName=Thread-3 : 2 号工人 start 2 号任务 
threadName=Thread-2 : 1 号工人 end 1 号任务 
threadName=Thread-3 : 2 号工人 end 2 号任务 
threadName=Thread-1 : 0 号工人 end 0 号任务 

スレッドプールconcurrent.futures

Python 3.2以降、標準ライブラリは、ThreadPoolExecutor(スレッドプール)を提供するconcurrent.futuresモジュールを提供します。

スレッド化などのモジュールと比較して、モジュールは送信を通じて将来のオブジェクトを返します。これは将来有望なオブジェクトであり、スレッドのステータスと戻り値を取得できます。

import random
import time
import threading
from concurrent.futures import ThreadPoolExecutor


def doing(person, task):
    thread_name = threading.current_thread().name
    print("threadName=%s : %s start %s " % (thread_name, person, task))
    time.sleep(random.randrange(start=1, stop=5))
    print("threadName=%s : %s end %s " % (thread_name, person, task))
    return thread_name


def test3():
    # 创建一个最大容纳数量为2的线程池
    with ThreadPoolExecutor(max_workers=3) as executor:
        items = []
        for i in range(0, 3):
            item = executor.submit(doing, "%d 号工人" % i, "%d 号任务" % i)
            items.append(item)

        results = []
        for item in items:
            results.append(item.result())

        print(results)


if __name__ == "__main__":
    test3()

演算結果:

threadName=ThreadPoolExecutor-0_0 : 0 号工人 start 0 号任务 
threadName=ThreadPoolExecutor-0_1 : 1 号工人 start 1 号任务 
threadName=ThreadPoolExecutor-0_2 : 2 号工人 start 2 号任务 
threadName=ThreadPoolExecutor-0_0 : 0 号工人 end 0 号任务 
threadName=ThreadPoolExecutor-0_2 : 2 号工人 end 2 号任务 
threadName=ThreadPoolExecutor-0_1 : 1 号工人 end 1 号任务 
['ThreadPoolExecutor-0_0', 'ThreadPoolExecutor-0_1', 'ThreadPoolExecutor-0_2']

future.result(timeout = None):スレッドの実行結果を取得します。実行が完了していない場合は、結果が出るまで待機します(またはタイムアウトを待機します)。

ThreadPoolExecutor-0_2がThreadPoolExecutor-0_1よりも早く終了した場合でも、上記のすべての結果は実行順序と同じ順序になります。

as_completed

誰でもそれを実行すると、より早く結果が得られます。スレッドプール内の子スレッドの実行が終了したら、すぐにスレッドに戻り、result()を使用して返された結果を取得します。上記のように、実行順序で結果を取得しないでください。

def test3():
    # 创建一个最大容纳数量为2的线程池
    with ThreadPoolExecutor(max_workers=3) as executor:
        items = []
        for i in range(0, 3):
            item = executor.submit(doing, "%d 号工人" % i, "%d 号任务" % i)
            items.append(item)

        results = []
        # for item in items:
        for item in as_completed(items):
            results.append(item.result())

        print(results)

演算結果:

threadName=ThreadPoolExecutor-0_0 : 0 号工人 start 0 号任务 
threadName=ThreadPoolExecutor-0_1 : 1 号工人 start 1 号任务 
threadName=ThreadPoolExecutor-0_2 : 2 号工人 start 2 号任务 
threadName=ThreadPoolExecutor-0_1 : 1 号工人 end 1 号任务 
threadName=ThreadPoolExecutor-0_0 : 0 号工人 end 0 号任务 
threadName=ThreadPoolExecutor-0_2 : 2 号工人 end 2 号任务 
['ThreadPoolExecutor-0_1', 'ThreadPoolExecutor-0_0', 'ThreadPoolExecutor-0_2']

おすすめ

転載: blog.csdn.net/fangye1/article/details/112248260