#概要
pythonのthreadで排他制御やってみた。
#衝突する方。
https://paiza.io/projects/MtUgwYIFZBn8NddHPRtPIA
import threading
import time
counter = 5
class MyThread(threading.Thread):
def __init__(self, name, sleep_time):
threading.Thread.__init__(self)
self.name = name
self.sleep_time = sleep_time
def run(self):
global counter
count = counter
print (self.name + ': read counter ' + str(counter))
print (self.name + ': do something')
time.sleep(self.sleep_time)
counter = count - 1
print (self.name + ': write counter ' + str(counter))
thread1 = MyThread('a', 1)
thread2 = MyThread('b', 0.1)
thread1.start()
time.sleep(0.1)
thread2.start()
thread1.join()
thread2.join()
print ('counter: ' + str(counter))
#排他制御
https://paiza.io/projects/20N5eisHzIeRQ08XNG4dVg
import threading
import time
counter = 5
lock = threading.Lock()
class MyThread(threading.Thread):
def __init__(self, name, sleep_time):
threading.Thread.__init__(self)
self.name = name
self.sleep_time = sleep_time
def run(self):
global counter
global lock
lock.acquire()
count = counter
print (self.name + ': read counter ' + str(counter))
print (self.name + ': do something')
time.sleep(self.sleep_time)
counter = count - 1
print (self.name + ': write counter ' + str(counter))
lock.release()
thread1 = MyThread('a', 1)
thread2 = MyThread('b', 0.1)
thread1.start()
time.sleep(0.1)
thread2.start()
thread1.join()
thread2.join()
print ('counter: ' + str(counter))
以上。