Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python threading.Event: add event params

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.

like image 204
acrilige Avatar asked Oct 02 '13 20:10

acrilige


2 Answers

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()
like image 99
abarnert Avatar answered Oct 09 '22 07:10

abarnert


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.

like image 42
shx2 Avatar answered Oct 05 '22 11:10

shx2