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