問題一覧に戻る
上級パフォーマンスと並行処理
問題117: multiprocessing基礎
multiprocessingモジュールは、プロセスベースの並列処理を提供します。ProcessクラスやPoolクラスを使用して、複数のCPUコアを活用した真の並列実行が可能です。GILの制約を受けないため、CPUバウンドなタスクで高いパフォーマンスを発揮します。
# multiprocessing基礎
import
# ワーカー関数
def square(n):
return n * n
# メインチェック
if __name__ == "__main__":
# プールを作成
with multiprocessing.() as pool:
numbers = [1, 2, 3, 4, 5]
# 関数をマップ
results = pool.(square, numbers)
print(f"Results: {results}")