[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Asynchronous IO with Pygame



hi,

Use the fastevent module, that's thread safe.

import pygame

event_get = pygame.fastevent.get
event_wait = pygame.fastevent.wait
event_post = pygame.fastevent.post


Note, that normal event.post raises an exception if it can't post an
event.  So you can make it retry posting a number of times until it is
successful(or you give up).  You can get into a deadlock situation if
multiple things are trying to post at the same time.  So event.post
could be classified thread safe... it's just not very performant.


fastevent should solve your issues.  Just be sure to use either
fastevent or event, not both.



cu!




On Sat, Nov 29, 2008 at 11:43 AM, Weeble <clockworksaint@xxxxxxxxx> wrote:
> Hi, I'm new to the list. Looking at the recent archive, I noticed that
> somebody said that pygame.event.post is not thread-safe. Is this true?
> I am trying to do asynchronous IO (communicating with another process)
> and this was my only good solution.
>
> For various reasons, I would like to run Pygame in one process and
> send messages to it from another. One reason for this is so that I can
> use an interactive Python shell to interact with my Pygame
> application. I'm using multiprocessing and sending messages via an
> interprocess queue. However, this gives me a dilemma in the Pygame
> process. If I make a blocking call to event.get() or something like
> that, I'll not be able to respond to messages coming in on the queue.
> If I make a blocking call to read from the queue, I can't pump
> messages. I can poll them constantly, but then I have to trade off
> responsiveness with wasted CPU time. My application doesn't do
> animation and I'd really like it not to be waking up unless it really
> needs to. I thought I could achieve this by having a helper thread
> that lives only to read from the queue and post Pygame events. Indeed,
> this appears to work, but if event.post isn't guaranteed thread-safe
> then I guess I may be inviting trouble.
>
> Is this possible? Is there another way to get the same effect without
> polling? Is this what the fastevent module is for?
>
> I have uploaded an example here:
>
> http://pastebin.com/f79e512b1
>
> Save it as, e.g. example.py, then do:
>
> import example
> process, queue = example.start_pygame_process()
> queue.put("Hello world!")
>
> Any string you put on the queue will appear in the window, as well as
> a counter that increments on each redraw.
>