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

[pygame] Asynchronous IO with Pygame



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.