Python share CPU time?

enigmadude at rock.com enigmadude at rock.com
Wed Aug 9 14:41:06 EDT 2006


There's several ways of doing concurrency in Python. Other than the
threading module, have you tried FibraNet? It's designed with simple
games in mind.
You can download it at http://cheeseshop.python.org/pypi/FibraNet.
Specifically the nanothreads module from FibraNet uses generators to
simulate light-weight cooperative threads.

Generator-based approaches are fast and *deterministic*, unlike true
threads where you have to account for race conditions, etc. You can
pause, resume, kill, or end a "thread". In Python 2.5 (soon to be
released), generators will be consumers rather than just producers, so
you can pass things into generators (without needing global variables
as a workaround) rather than only being able to spit out data
on-the-fly. They'll also have a more graceful way to handle exceptions.

For a good overview of the concept, especially if you want to implement
this yourself instead of using Fibranet (although re-use is often the
better choice), take a look at this link from the Charming Python
column:
http://gnosis.cx/publish/programming/charming_python_b7.html.

If this all seems too exotic, then you can also just go with the
traditional threading approach with the threading module. Normally
you'll want to use the "threading" module rather than the lower-level
"thread" module. But be warned, threads are a big can of worms.

I hope you find this useful.

Yannick wrote:
> Hi,
>
> I would like to program a small game in Python, kind of like robocode
> (http://robocode.sourceforge.net/).
> Problem is that I would have to share the CPU between all the robots,
> and thus allocate a time period to each robot. However I couldn't find
> any way to start a thread (robot), and interrupt it after a given time
> period.
> Any suggestions on how to proceed?
> Is Python just not adapted to this kind of things?
> 
> Thanks,
> Yannick




More information about the Python-list mailing list