6

Can I use Event object from threading module not only to notify that some event has happened but also to give some params of this event, for example:

e = Event()
...
e.param = "this is event data"
e.set()

Another thread:

e.wait()
data = e.param

It seems to be ok at first glance, but are there any problems than can happen? Is it safe? If not, what other way is better to pass some events params between threads?

Thanx.

2
  • As a side note, it sounds like you're probably trying to use an Event as a Condition. Commented Oct 2, 2013 at 20:51
  • This only works once unless you have other logic to control when param can be read/written. A Queue may be a better choice. Commented Oct 2, 2013 at 20:54

2 Answers 2

7

You don't really need to attach the value to the Event object, you can just use some other global, attribute, etc. separate from the Event, and use the Event to signal that it's been updated. And that's the usual way of doing things.

But there's really nothing wrong with what you're doing. And it doesn't add any other problems beyond the usual race problems with using events for signaling. However, it does seem a bit misleading—it makes it seem as if the param is somehow synchronized, when it isn't.

If you're trying to signal that a new value is ready, and synchronize access to that value you almost always want a Condition, like this:

c = Condition()
data = None
...

with c:
    data = "new data"
    c.notify()

...

with c:
    while data is None:
        c.wait()

Or, more simply, just use a queue and don't share a variable in the first place:

q = Queue()

...

q.put(data)

... 

data = q.get()
Sign up to request clarification or add additional context in comments.

Comments

0

One potential problem with this approach is that if the event is being set rapidly, the param can be overwritten before the waiting thread reads the older value.

A more standard approach for such inter-thread message-passing is using Queue.Queue. However, the limitation with a queue-based solution is that only one thread can read the message. In other words: the reader consumes the message. This approach is ideal for producer-consumer paradigms. (You didn't mention whether you have multiple threads waiting on the event).

For multiple reader-threads, you should also consider a pubsub (publisher/subscriber) solution, although I am unaware of any out-of-the-box pubsub implementation in python.

2 Comments

No, multiple threads can read a queue. Thread pools can be implemented easily with a single queue.
Actually in my case every event is used only one time (it means that it is being set only one time)

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.