Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I tried implementing the exclusive queue as given in the Little book of semaphores. But I suspect there's a deadlock occurring as i see no progress. Not able to figure out the issue. Any pointers would be helpful.

from threading import Thread, Semaphore
class Queue:
def __init__(self):
    self.leaders = 0
    self.followers = 0
    self.mutex= Semaphore(1)
    self.leaderQ = Semaphore(0)
    self.followerQ = Semaphore(0)
    self.renz = Semaphore(0)

def dance(self, who, i):
    print i, ' ', who, " is dancing tra ling"

def leader(self, i):
    self.mutex.acquire()
    if self.followers > 0:
        self.followers -= 1
        self.followerQ.release()
    else:
        self.leaders += 1
        self.mutex.release()
        self.leaderQ.acquire()
    self.dance('leader ', i)
    self.renz.acquire()
    self.mutex.release()

def follower(self, i):
    self.mutex.acquire()
    if self.leaders > 0:
        print i, " is dancing tra ling"
        self.leaders -= 1
        self.leaderQ.release()
    else:
        self.followers += 1
        self.mutex.release()
        self.followerQ.acquire()
    self.dance('follower ', i)
    self.renz.release()

class Worker(Thread):
def __init__(self, q, i):
    Thread.__init__(self)
    self.q = q
    self.i = i

def run(self):
    self.q.follower(i)
    self.q.leader(i)

qu = Queue()

for i in range(2):
print('doing :', i)
Worker(qu, i).start()
share|improve this question

closed as off-topic by Brian Reichle, Gareth Rees, svick, Uri Agassi, Marc-Andre Feb 27 at 21:33

This question appears to be off-topic. The users who voted to close gave these specific reasons:

  • "Your question must contain working code for us to review it here. For questions regarding specific problems encountered while coding, try Stack Overflow. After getting your code to work, you may edit this question seeking a review of your working code." – Uri Agassi, Marc-Andre
  • "This question does not appear to be a code review request within the scope defined in the help center. Please see the FAQ about off-topic questions." – Brian Reichle, Gareth Rees, svick
If this question can be reworded to fit the rules in the help center, please edit the question.

1  
On Code Review we review working code (see the FAQ): for help with code that doesn't work, try Stack Overflow. –  Gareth Rees Dec 21 '12 at 13:47

1 Answer 1

In Worker.run() both of your threads are running Queue.follower() so they both end up blocked on followerQ, and neither of them ever runs Queue.leader().

I think your Queue is correct, but for it to work properly, you have to make sure there is at least

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.