Pygame and threading: locked when accessing to globals?
I am programming a game using pygame. I intend to control one of the characters using OpenSoundControl (OSC), a udp-based protocol for realtime communication. Basically I am using simpleOSC module to biund some OSC commands to functions on my pygame program.
My game structure is something like this (this is a simplification so you get the idea):
globalsomething = {}
def handler(*m):
global globalsomething
print "it works"开发者_高级运维
print globalsomething
print "not working"
if __name__ == "__main__":
osc.init()
osc.listen('', 3333)
osc.bind(handler,'/game/dosmtng')
app = Game()
while True:
app.MainLoop()
Game is a simple class that executes pygame.init() and draws and does pretty much everything related to pygame.
The problem I get when executing the code is that when I send an osc packet I get "It works" but not "not working" and then no subsequent osc packets are processed.
Since simpleOSC uses threads, my only explanation to this behavior is that pygame uses some kind of incompatible threading (?) and when trying to access to a variable located in pygame's thread it locks.
Any ideas about the cause and (if possible) a solution?
I can't verify whether you are in fact having a thread/concurrency issue, although it seems likely. I can suggest a solution that may resolve it.
The python multiprocessing module demonstrates how to spawn a new process (not a thread) with a queue. If you create the new process and then init OSC in there, and have the handler simply put a message on the queue whenever something arrives, you can then poll the queue from the main pygame process to obtain any messages that have come in.
It's a bit less clean than you might like, but at least it'll get the two modules at arms length so they can't interfere with each other.
精彩评论