Python中的连续读/写线程同步

时间:2016-08-04 07:35:31

标签: python multithreading synchronization readerwriterlock

我正在尝试实现Reader / Writer锁定机制来控制3个线程的同步,每个线程基于骰子的随机抽取执行4次。例如,对于线程i,调用random.randint(1,6),如果输出是偶数,则读取线程i,如果是奇数,则线程i是写入。 Here我找到了读取器/写入器锁的一般实现,但是我没有成功地为3个线程执行这4个操作。这里是原始代码的一部分以及最后添加的内容:

import threading
import time, random
class RWLock:
    def __init__(self):
        self.rwlock = 0
        self.writers_waiting = 0
        self.monitor = threading.Lock()
        self.readers_ok = threading.Condition(self.monitor)
        self.writers_ok = threading.Condition(self.monitor)
    def acquire_read(self):
        self.monitor.acquire()
        while self.rwlock < 0 or self.writers_waiting:
            self.readers_ok.wait()
        self.rwlock += 1
        self.monitor.release()
    def acquire_write(self):
        self.monitor.acquire()
        while self.rwlock != 0:
            self.writers_waiting += 1
            self.writers_ok.wait()
            self.writers_waiting -= 1
        self.rwlock = -1
        self.monitor.release()
    def release(self):
        self.monitor.acquire()
        if self.rwlock < 0:
            self.rwlock = 0
        else:
            self.rwlock -= 1
        wake_writers = self.writers_waiting and self.rwlock == 0
        wake_readers = self.writers_waiting == 0
        self.monitor.release()
        if wake_writers:
            self.writers_ok.acquire()
            self.writers_ok.notify()
            self.writers_ok.release()
        elif wake_readers:
            self.readers_ok.acquire()
            self.readers_ok.notifyAll()
            self.readers_ok.release()

rwl = RWLock()

class Reader(threading.Thread):
    def run(self):
        print "Thread " + str(threading.active_count()) + " is now ready for reading shard location\n"
        rwl.acquire_read()
        time.sleep(5)
        print "Thread " + str(threading.active_count()) + " now has finished reading shard location\n"
        rwl.release()
        time.sleep(0.2)
        self._is_running = False

class Writer(threading.Thread):
    def run(self):
        print "Thread " + str(threading.active_count()) + " is now ready to write to shard location\n"
        rwl.acquire_write()
        time.sleep(5)
        print "Thread " + str(threading.active_count()) + " now has finished writing to shard location\n"
        rwl.release()
        time.sleep(0.2)
        self._is_running = False

alpha = list("ABC")
d = {i: 4 for i in alpha}

def execute(thread):
    global d
    diceDraw = random.randint(1, 6)
    if diceDraw % 2 == 0:
        thread = Reader()
        thread.start()
        time.sleep(1)
    else:
        thread = Writer()
        thread.start()
        time.sleep(1)

while sum(d.values()) > 0:
    for i in d.keys():
        if i:
            execute(i)
            d[i] -= 1

任何建议?

0 个答案:

没有答案