1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Python】threadingによる並列処理(非同期処理)

Last updated at Posted at 2022-11-21

マルチプロセスとの使い分け

  • CPU負荷の高い処理(CPU bound)は、マルチプロセス(multiprocessing)
  • I/Oの待ち時間が大きい処理(I/O bound、いわゆる非同期処理)は、マルチスレッド(threading)

並列処理コード

ParallelProcessingに並列処理を行いたい関数とスレッドを跨ぐたびに引数を更新する関数を入れる。
functionとupdateでそれらを記述する。

sample_threading.py
from threading import Timer
import time

# 並列処理を行うClass
class ParallelProcessing(Timer):
  def __init__(self, interval, function, update, args={}, kwargs={}):
    # Timerクラスのメンバー関数を呼び出して展開している
    Timer.__init__(self, interval, self.run, args, kwargs)
    self.thread = None
    self.function = function
    self.update = update
    self.function.counter = 0

  def run(self):
    self.thread = Timer(self.interval, self.run)
    self.thread.start()
    self.function(**self.args, **self.kwargs)
    self.args = self.update(**self.args)

  def cancel(self):
    if self.thread is not None:
      self.thread.cancel()
      self.thread.join()
      del self.thread

# 並列に処理を行いたい関数
def function(**kwargs):
    function.counter += 1
    print(kwargs['key'], function.counter)

# 引数を各スレッドで更新する
def update(**kwargs):
    updated_kwargs = {}
    for key, val in kwargs.items():
        if key == 'key':
            val = val + 'Hello'
            updated_kwargs[key] = val
    return updated_kwargs

if __name__=='__main__':
    process = ParallelProcessing(0.5, function, update, {"key":"Hello"})
    # 並列処理 開始
    process.start()
    time.sleep(10)
    # 並列処理 停止
    process.cancel()

同じファイルに非同期で同時にアクセスしたい場合

ロックを取得してからファイルに書き込むことで、同時アクセスを制御する。

import threading

lock = threading.Lock()

def write_to_file(data):
    with lock:
        with open('file.txt', 'a') as file:
            file.write(data)
for i in range(1000):
    thread1 = threading.Thread(target=write_to_file, args=('aaa'))
    thread1.start()
thread1.join()

まとめ

theadingを用いた並列処理をやってみた。覚書として、記事にまとめておく。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?