1
2

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 複数スレッドから同時アクセスされたときに前回のアクセス時間よりも2秒以上経過していなければ待機して、経過後にアクセス時間を記録して、この値をreturnする処理

Last updated at Posted at 2022-03-23

以下は、複数スレッドから同時アクセスされたときに前回のアクセス時間よりも2秒以上経過していなければ待機して、経過後にアクセス時間を記録して、この値をreturnする処理

import time
import threading

lock = threading.Lock()

access_time = time.time()


def task():
    while True:
        print(concurrent_access())
        pass


def concurrent_access():
    """複数スレッドに同時にアクセスされるかもしれない処理"""
    # 前回のアクセス時間より2秒以上経過して "いる"
    #   access_timeを現在時刻にしてから
    #   access_timeをreturn
    # 前回のアクセス時間より2秒以上経過して 'いない"
    #   2秒経過するまで待機
    #   2病経過したら上と同じ処理
    global access_time
    try:
        # 現在のスレッド名を表示
        print(threading.current_thread().name)
        lock.acquire()
        while True:
            if access_time + 2 < time.time():
                access_time = time.time()
                return access_time
    finally:
        lock.release()


ths = []
for i in range(3):
    th = threading.Thread(target=task, name=f'thread{i}')
    th.start()
    ths.append(th)
for th in ths:
    th.join()

実行結果
thread0
thread1
thread2
1648015757.6682205
thread0
1648015759.6691394
thread1
1648015761.6700594
thread2
1648015763.6702552
thread0
1648015765.671093
thread1
1648015767.6731405
thread2
1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?