Tell me more ×
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
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

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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