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.

When I read some code,I think the usage of Event is not necessary,is it right?

# start server
while True:
    # accept a request here
    queue.put(info)
    event.set() # notify all the threads?
    # pass queue and event here to a Thread constructor

other place there are more than 10 threads running,

# inside a Thread class
def __init__(self, queue, event):
    threading.Thread.__init__(self)
    self.queue, self.event = queue, event

def run(self):
    while True:
        self.event.wait() # <- block here, I think this can be removed
        info = self.queue.get() # <- block here again, only one thread can get job to do?
        # do something
        self.queue.task_done()
        self.event.clear() #
share|improve this question
In the small snippets of code that you posted, it does indeed seem that event is unnecessary. Furthermore, it seems as if event is global, which is probably not a good idea either, if it is to be used, event should be stored as an instance variable of the thread class. – Joel Cornett Jul 17 '12 at 1:49
They are not global,I have updated the snippet. – iMom0 Jul 17 '12 at 7:42

2 Answers

up vote 1 down vote accepted

As long as queue is actually Queue.Queue (or another collection with its own blocking mechanic), the event object is not required in the code you posted. I'd even say that it's used incorrectly. There is a racing condition when the server calls event.set() and a thread is just done with its current task, calling event.clear(). This leaves all threads waiting on the event, even though there's an item in the queue.

Edit: Bollocks, didn't think that one through. event.set() wakes up all threads that are hanging on event.wait(), causing them to continue waiting at queue.get(). One thread will fetch the item and process it. So, no racing condition. Just redundancy.

share|improve this answer
IOW Queue.Queue is thread-safe. – Joel Cornett Jul 17 '12 at 17:04

The Queue module has implemented multi-producer, multi-consumer queues, which is thread-safe.So you can remove event object.The queue.get() will block there and wait something to happen that you expected.

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.