0
1

More than 3 years have passed since last update.

lockとRlock

Last updated at Posted at 2020-04-17
import logging
import threading
import time

logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s')


def worker1(d, lock):
    logging.debug('start')

    #with lockのブロック内の処理が終わるまで他のスレッドは処理されない
    with lock:
        i = d['x']
        time.sleep(5)
        d['x'] = i + 1
        logging.debug(d)

        #main関数でlock = threading.Lock()とした場合は処理が進まなくなる
        with lock:
            d['x'] = i + 1
    logging.debug('end')

def worker2(d, lock):
    logging.debug('start')

    #lock.acuire()とlock.releaseで囲まれた部分の処理が終わるまで他のスレッドは処理されない
    lock.acquire()
    i = d['x']
    d['x'] = i + 1
    logging.debug(d)
    lock.release()
    logging.debug('end')


if __name__ == '__main__':
    d = {'x': 0}
    lock = threading.RLock()
    t1 = threading.Thread(target=worker1, args=(d, lock))
    t2 = threading.Thread(target=worker2, args=(d, lock))
    t1.start()
    t2.start()
出力
Thread-1: start
Thread-2: start
Thread-1: {'x': 1}
Thread-1: end
Thread-2: {'x': 2}
Thread-2: end
0
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
0
1