Pythonでマルチスレッドを作成する方法
Pythonでは、マルチスレッドを作成するにはいくつかの方法がありますが、最も一般的に使用されている方法は次のとおりです。
- スレッド作成
- スレッド化
- スレッド
- スタート
import threading
def my_function():
# 你的代码
thread = threading.Thread(target=my_function)
thread.start()
- スレッド
- スレッド
- run()をネイティブで日本語に言い換えると: 実行()
import threading
class MyThread(threading.Thread):
def run(self):
# 你的代码
thread = MyThread()
thread.start()
- シーケンシャルではなく平行に実行する
- 同時のフューチャ
- スレッドプールエグゼキュータ
- プロセスプールエグゼキュータ
import concurrent.futures
def my_function():
# 你的代码
with concurrent.futures.ThreadPoolExecutor() as executor:
executor.submit(my_function)
- マルチプロセッシング
- マルチプロセッシング
import multiprocessing
def my_function():
# 你的代码
thread = multiprocessing.Process(target=my_function)
thread.start()
Python のマルチスレッドは GIL (Global Interpreter Lock) の存在により、真の並列実行はできない点に注意。並列実行を実現したい場合は、マルチプロセスを検討する必要があります。