开发者

Multiple Threads subscribing same event

What will happen when 10 threads will subscribe to the same event and the event fires? W开发者_如何学Pythonhich thread will pick it up?


Thread's don't subscribe to events, objects do. When an event fires, all of the registered handlers execute on the same thread (the one that raised the event). There's no built-in facility for events to fire on multiple threads.

A handler can choose to forward the event information to a separate thread, if desired, but that's not part of the built-in mechanism of event dispatch.


If by "event" you mean a Win32 synchronization Event (which is how I read the question) then it depends on how the EventWaitHandle is created. If its manual reset, the event will signal all threads and all will execute. If its auto reset, a single thread will be signalled and executed. Any of your 10 threads waiting on the event could be chosen.


I think what you mean here is that multiple objects on separate threads subscribe to an event.

All of the handlers will be called but on the same thread that invoked the event.


The answer to your question I guess is it depends on the implementation of the event dispatcher... Usually you use a list to keep track of all the event handlers which subscribed to a particular event, so most likely in terms of this kind of implementation, the first handler that gets fired is the first event handler that got subscribed if you of course call all the relevant procedures synchronously, if not, then it depends... just a thought..


If you want to know which object will pick up the event, every object that subscribes to an event will pick up that event, but each will run on the thread that the event occurred on.

If you want to know which object will pick up that event first see ultrajohns answer.


I think if I understand your question. You mean to ask your object exposes a event that user of your object can subscribe. If 10 different users of your object has subscribed to this event, and at some point you fire the event, what would be order (or simultaneously) the event handlers would be invoked?

Answer: Since the event handler execution happens on the same thread who fires it (in this case your object's processing thread) can only process one handler function at a time. The order is not guaranteed (meaning not necessarily first subscriber would executed first and last would be executed last). I hope this answers your question. The bottom line is all 10 handler would be called and none would be in parallel. They will be executed one after another. I have seen people accidentally subscript to save event twice and then seeing the action happening twice and having hard time figuring out why some things are happening multiple times.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜