Pythonでマルチスレッドを作成する方法

Pythonでは、マルチスレッドを作成するにはいくつかの方法がありますが、最も一般的に使用されている方法は次のとおりです。

  1. スレッド作成
  2. スレッド化
  3. スレッド
  4. スタート
import threading

def my_function():
    # 你的代码

thread = threading.Thread(target=my_function)
thread.start()
  1. スレッド
  2. スレッド
  3. run()をネイティブで日本語に言い換えると: 実行()
import threading

class MyThread(threading.Thread):
    def run(self):
        # 你的代码

thread = MyThread()
thread.start()
  1. シーケンシャルではなく平行に実行する
  2. 同時のフューチャ
  3. スレッドプールエグゼキュータ
  4. プロセスプールエグゼキュータ
import concurrent.futures

def my_function():
    # 你的代码

with concurrent.futures.ThreadPoolExecutor() as executor:
    executor.submit(my_function)
  1. マルチプロセッシング
  2. マルチプロセッシング
import multiprocessing

def my_function():
    # 你的代码

thread = multiprocessing.Process(target=my_function)
thread.start()

Python のマルチスレッドは GIL (Global Interpreter Lock) の存在により、真の並列実行はできない点に注意。並列実行を実現したい場合は、マルチプロセスを検討する必要があります。

bannerAds