1
\$\begingroup\$

For the first readers-writers problem, in which readers can access a given resource simultaneously, is the following Python3 solution correct?

Problem parameters:

  • One set of data is shared among a number of threads
  • Only one writer may write at a time, and no other thread can read the resource
  • If at least one reader is reading, no other thread can write
  • Multiple readers can read the resource without blocking each other
import threading, time
from multiprocessing import Condition


class SharedResource():
    def __init__(self):
        self.val = 0

# The class solving this problem
class RWLock:
    def __init__(self):
        self.cond = Condition()
        self.readers = 0

    def read_acquire(self):
        self.cond.acquire()
        self.readers += 1
        self.cond.release()

    def read_release(self):
        with self.cond:
            self.readers -= 1
            if (self.readers == 0):
                self.cond.notify_all()

    def write_acquire(self):
        self.cond.acquire()
        if (self.readers > 0):
            self.cond.wait()

    def write_release(self):
        self.cond.release()


def read(lock, res):
    while True:
        lock.read_acquire()
        print(threading.current_thread().ident, "Reading:",res.val)
        time.sleep(0.5)
        lock.read_release()

def write(lock, res):
    while True:
        lock.write_acquire()
        print(threading.current_thread().ident, "Writing")
        res.val += 1
        time.sleep(1)
        lock.write_release()


if __name__ == '__main__':
    lock = RWLock()
    res = SharedResource()

    for i in range(10):
        t = threading.Thread(target=read, args=(lock,res,))
        t.start()

    for i in range(10):
        t = threading.Thread(target=write, args=(lock,res,))
        t.start()

I did not find any solution online using a single condition, and have been trying to find a loophole in this one. From what I have gathered, it fulfills the problem's requisites.

Two questions:

  • Does the solution fulfill the problem's requisites?
  • Is the above code correct?

What are your thoughts on this?

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to Code Review! Please post the (abbreviated) challenge description with your question. Also please note that checking the correctness of your code is not what this site is about. \$\endgroup\$ – AlexV May 5 at 19:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.