LoginSignup
5
8

More than 5 years have passed since last update.

pythonのthreadで排他制御

Last updated at Posted at 2017-11-19

概要

pythonのthreadで排他制御やってみた。

衝突する方。

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))

排他制御

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))


以上。

5
8
1

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
5
8