Shehzaad
Shehzaad

Reputation: 25

Threads in Python 2.7

I'm new to Python. I tried to code the readers-writers problem with a stron reader priority, for some reason, python doesn't consider my global variable 'nor'. Is there an issue with the thread definition?

import threading

readers=threading.BoundedSemaphore(1)

writers=threading.BoundedSemaphore(1)

mutex=threading.BoundedSemaphore(1)

nor=0
class reader(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        while(1):
            writers.acquire()
            mutex.acquire()
            if(nor==0):
                readers.acquire()
            nor=nor+1
            mutex.release()

            print "I just read\n"

            mutex.acquire()
            if(nor==1):
                readers.release()

            nor=nor-1
            mutex.release()
            writers.release()

class writer(threading.Thread):
  def _init__(self):
          threading.Thread.__init__(self)
  def run(self):
      while(1):        
         writers.acquire()
         readers.acquire()

        print "I just wrote\n"

        writers.release()
        readers.release()

r1=reader()
r2=reader()
r3=reader()
w1=writer()
w2=writer()

r1.start()
r2.start()
r3.start()
w1.start()
w2.start()

Upvotes: 1

Views: 1381

Answers (1)

Juan Gallostra
Juan Gallostra

Reputation: 301

Try tiping

global nor

inside your class, before the nor call. After

def run(self): 

Upvotes: 2

Related Questions