Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add pygame events from a second thread

Well I have read at various places that the pygame event handling must be done in the main thread. I want to do that but my question is, can I add events to the event queue from a different thread?

I want to call pygame.event.post(myEvent) from a different thread and than handle the event in the main loop. Is this possible?

edit: To clarify, I want to run a separate thread for asynchronous network i/o. When a new message arrived the thread would then put an event in the event queue to signal there is something to do.

like image 722
BubuIIC Avatar asked Mar 21 '13 02:03

BubuIIC


People also ask

How to create a second userevent in Pygame?

For creating a second event, you would do pygame.USEREVENT + 1 (for an ID of 25), and so on. (The +0 in the above code is just for conceptual purposes). Due to limitations imposed by pygame, only 9 UserEvents can exist at a given time, from values 24 – 32. Creating a Pygame UserEvent is just the first step.

What's new in Pygame?

New in pygame 1.9.2. When compiled with SDL2, pygame has these additional events and their attributes. New in pygame 1.9.5. Changed in pygame 2.0.2: Fixed amount horizontal scroll (x, positive to the right and negative to the left). Changed in pygame 2.0.2: The touch attribute was added to all the MOUSE events.

What is an eventtype object in Pygame?

An EventType event object contains an event type identifier and a set of member data. The event object contains no method functions, just member data. EventType objects are retrieved from the pygame event queue. You can create your own new events with the pygame.event.Event() function.

What happens when a timeout is given in Pygame?

From pygame 2.0.0, if a timeout argument is given, the function will return an event of type pygame.NOEVENT if no events enter the queue in timeout milliseconds. The event is removed from the queue once it has been returned. While the program is waiting it will sleep in an idle state.


1 Answers

Time for some detective work!

Looking at the source for event_post in event.c indicates that the C function uses the SDL call SDL_PushEvent, without checking for thread-safety on its own. However, the documentation for SDL_PushEvent says:

This function is thread safe, and can be called from other threads safely.

So it seems that it is indeed thread-safe.

like image 65
Claudiu Avatar answered Sep 28 '22 10:09

Claudiu