1

I have a class, for example like the following

Class Example(object):
   trigger_event = threading.Event()

    def set_trigger(self):
        # do some stuff
        self.trigger_event.set()

What I am finding is if I have a group of these objects and process them in a single thread, then once the first object has its event set, then all other objects have it set as well. Is there no way to have a unique Event member for each individual object?

If I have 10 objects, and print out the is_set() for the Event before I call set_trigger() then it will show as FALSE, TRUE, TRUE, TRUE etc...

Thanks in advance for any help or insight!

1 Answer 1

1

You are probably misinterpreting the Event object. The Event object is used for communication between multiple threads: one thread signals an event and other threads wait for it.

An event object manages an internal flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.

But if you still want to do that, you have to create new event object every time you create new instance of Example. So you might have to do something like,

class Example(object):
    def __init__(self):
        self.trigger_event = threading.Event()

    def set_trigger(self):
        # do some stuff
        self.trigger_event.set()

e1 = Example()
print(e1.trigger_event.is_set())
e1.set_trigger()
print(e1.trigger_event.is_set())

e2 = Example()
print(e2.trigger_event.is_set())
e2.set_trigger()
e2.trigger_event.wait()
print(e2.trigger_event.is_set())

Output:

False
True
False
True
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, you are right - your approach works for my instance. In my actual example I have two threads - a parser and a DB thread, and I needed a way for the parser to know when the DB processed its request so using the event and your suggestion made it work! Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.