python multiprocessingを使って並列処理を行う

pythonで、multiprocessingを使用して、並列処理を行うサンプルコードを記述してます。pythonのバージョンは3.8.5を使用してます。
環境
- OS windows10 pro 64bit
- python 3.8.5
multiprocessing使い方
multiprocessingを使用すると、並列処理を行うことが可能です。
import multiprocessing
if __name__ == "__main__":
p1 = multiprocessing.Process(name="プロセス名", target=実行する関数, args=(引数,))
「if name == ‘main’:」がないとエラーとなります。
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
以下は、2秒ごとに実行されるprocessと、6秒ごとに実行されるprocessを並列処理したコードとなります。
import multiprocessing
import time
def worker(t):
for n in range(5):
time.sleep(t)
print("%s %d回目の実行" % (multiprocessing.current_process().name, n+1))
if __name__ == "__main__":
# 2秒ごとに実行
process1 = multiprocessing.Process(name="process1", target=worker, args=(2,))
# 6秒ごとに実行
process2 = multiprocessing.Process(name="process2", target=worker, args=(6,))
# process開始
process1.start()
# process開始
process2.start()
実行結果

-
前の記事
SQL Server エラー「ロック要求がタイムアウトしました」が発生した場合の対処法 2021.03.16
-
次の記事
javascript WebカメラにWeb APIを使用してアクセスする 2021.03.17
コメントを書く