473,468 Members | 1,449 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Python share CPU time?

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

Aug 9 '06 #1
13 1650
On 2006-08-09, Yannick <ya***************@gmail.comwrote:
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.
The robot code thread needs to block when it runs out of things
to do.
Any suggestions on how to proceed?
Just start a thread for each robot, and put a call to
time.sleep(0.010) in the main loop for the robot code. Adjust
the 0.010 value to taste.

As an alternative to sleeping, you could wait for some sort of
event each time through the loop.
Is Python just not adapted to this kind of things?
It's quite well adapted to this sort of thing.

--
Grant Edwards grante Yow! Why don't you
at ever enter and CONTESTS,
visi.com Marvin?? Don't you know
your own ZIPCODE?
Aug 9 '06 #2
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...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
Aug 9 '06 #3
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?
>>import thread, time
def robot(name):
.... for i in xrange(5):
.... print "%s on pass %i" % (name, i)
.... time.sleep(0.01)
....
>>ids = [thread.start_new(robot, ("Robot%i" % i,)) for i in
xrange(4)]
Robot1 on pass 0
Robot2 on pass 0
Robot0 on pass 0
Robot3 on pass 0
Robot1 on pass 1
Robot0 on pass 1
Robot2 on pass 1
Robot3 on pass 1
Robot1 on pass 2
Robot0 on pass 2
Robot2 on pass 2
Robot3 on pass 2
Robot1 on pass 3
Robot0 on pass 3
Robot2 on pass 3
Robot3 on pass 3
Robot1 on pass 4
Robot0 on pass 4
Robot2 on pass 4
Robot3 on pass 4

Maintaining a Queue of things to do for each robot allows the
robot to process a single thing before sleeping a bit.

The thread scheduler does seem to provide interruptions, as I've
run the above code with no sleep() call and larger iterations,
and you'll find it bouncing from robot to robot.

Or, you can take advantage of python's yield statement:
>>class Robot(object):
.... def __init__(self, name):
.... self.name = name
.... self.thought = 0
.... self.done = False
.... def think(self):
.... while not self.done:
.... yield self.thought
.... self.thought += 1
.... def finish(self):
.... self.done = True
....
>>robots = [Robot(str(i)) for i in xrange(5)]
generators = [robot.think() for robot in robots]
[g.next() for g in generators]
[0, 0, 0, 0, 0]
>>[g.next() for g in generators]
[1, 1, 1, 1, 1]
>>[g.next() for g in generators]
[2, 2, 2, 2, 2]
>>[g.next() for g in generators]
[3, 3, 3, 3, 3]
>>[g.next() for g in generators]
[4, 4, 4, 4, 4]
>>generators[2].next()
5
>>[g.next() for g in generators]
[5, 5, 6, 5, 5]
>>robots[2].thought
6
>>robots[3].thought
5

Just do more complex stuff in the think() method (to most folks,
counting isn't very exciting thinking) and yield your current state.
Is Python just not adapted to this kind of things?
Python is quite adaptable to these sorts of things...it requires
an adaptable programmer to make the best use of it though... ;)

-tkc


Aug 9 '06 #4
On 2006-08-09, Tim Chase <py*********@tim.thechases.comwrote:
>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?
>import thread, time
def robot(name):
... for i in xrange(5):
... print "%s on pass %i" % (name, i)
... time.sleep(0.01)
>[...]
I originally suggested the thread/sleep() scheme, but after
thinking about it more, I really like the generator approach in
the case where you want to explicity end each robot's "turn"
using the CPU (which is what the sleep() call does).

OTOH, if you want the robots to wait for events of some sort
(e.g. from a queue) or data from an I/O device, then threading
is probably the way to go.

I guess it all depends on whether the robots' behavior is to be
time-driven or event-driven.

--
Grant Edwards grante Yow! Used staples are good
at with SOY SAUCE!
visi.com
Aug 9 '06 #5
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
You should take a look at stackless Python. It should do very nicely
for what you want. There is a good tutorial on it here:
http://members.verizon.net/olsongt/s...stackless.html

Aug 9 '06 #6
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?
If your intent is to allow the user to program a robot using python
then no it's NOT suitable. There's no builtin way to restrict what
code can do (but Zope might have a way), nor can you force it to pause
after a predetermined amount of time, nevermind making that amount of
time deterministic enough to be fair in a game.

However, if your intent was to have only trusted code then Python would
work fine. My preference would be for generators (especially once
Python 2.5 is released), but YMMV.

Aug 10 '06 #7
Thank you all for the detailled answers.

What I would like to achieve is something like:

# main loop
while True:
for robot in robots:
robot.start()
robot.join(0.2) # wait 200ms
if robot.is_active():
robot.stop()
# run all the game physics, pause, frame/rate, etc...

Unfortunately the stop() call doesn't exist in Python.

By using a generator I would make the assumption that every robot is
playing fair, and would yield often. But I cannot control this as
eventually robots would be coded by third parties.

Using Python scheduler would allow me to share time equally between
each robot, but then I would loose the ability to have a main thread
organizing everything.

Aug 10 '06 #8
Yannick wrote:
Thank you all for the detailled answers.

What I would like to achieve is something like:

# main loop
while True:
for robot in robots:
robot.start()
robot.join(0.2) # wait 200ms
if robot.is_active():
robot.stop()
# run all the game physics, pause, frame/rate, etc...

Unfortunately the stop() call doesn't exist in Python.

By using a generator I would make the assumption that every robot is
playing fair, and would yield often. But I cannot control this as
eventually robots would be coded by third parties.

Using Python scheduler would allow me to share time equally between
each robot, but then I would loose the ability to have a main thread
organizing everything.
This is just a dim memory, but something called lambdaMOO was (is?) a
Multi-User Dungeon that had (has?) a model of processing that allowed
you to create programmed objects that received a "budget" of processor
time. The objects would not work if they "ran out" of processor
time...

Perhaps something like this could help you? (Sorry to be so vague.)

HTH,
~Simon

Aug 11 '06 #9
Simon Forman wrote:
This is just a dim memory, but something called lambdaMOO was (is?) a
Multi-User Dungeon that had (has?) a model of processing that allowed
you to create programmed objects that received a "budget" of processor
time. The objects would not work if they "ran out" of processor
time...
It basically employs its own threading model to do just this.
SecondLife does much the same: any system that allows for the apparent
parallel running of code will.

LambdaMOO still exists, incidentally! You might also be interested in a
python-implemented version of the main MOO core, the unfortunately
named POO: http://www.strout.net/python/poo/

-alex23

Aug 11 '06 #10
Yannick wrote:
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?
You've gotten a number of other suggestions from other posters. Let me
suggest, though, as someone else has already beat me to, that
programming the robots in Python might not be ideal. Without some
significant work, you won't be able to prevent one of your "robots"
from tying up your Python interpreter for arbitrary lengths of time.
Consider, for example, a robot that executes the following line:

x = 10 ** 10 ** 10

Now, if you're careful, you *can* prevent this sort of thing. My guess
is, however, for a "small game," this effort is not going to be worth
it.
Is Python just not adapted to this kind of things?
That depends. I think Python would be a good choice of language to
implement a custom VM for such a game, where you could have the level
of control you need. Now, implementing a simple and limited-purpose VM
really isn't as hard as it sounds. The hard part comes if you want to
program your VM in anything other than its equivalent of Assembler.
Then, you basically need to write a Language X -VM compiler for
whatever Language X you'd really like to program in, and that's
generally not a trivial task.

Aug 11 '06 #11

alex23 wrote:
Simon Forman wrote:
This is just a dim memory, but something called lambdaMOO was (is?) a
Multi-User Dungeon that had (has?) a model of processing that allowed
you to create programmed objects that received a "budget" of processor
time. The objects would not work if they "ran out" of processor
time...

It basically employs its own threading model to do just this.
SecondLife does much the same: any system that allows for the apparent
parallel running of code will.
IIRC, LambdaMOO's threading model is based on cooperative multitasking,
possibly with the ability to limit how many VM-level instructions a
piece of code executes per timeslice (I'm not intimately familiar with
it). However, such an ability to limit how many instructions are
executed per timeslice really requires VM-level support.

In LPMUDs, which I am much more familiar with, and which also implement
a similar cooperative multitasking "thread model" (I put this in quotes
because it's not really threading -- it's actually a near equivalent of
generator-based microthreads), it's still possible to lag the game for
long periods of time with any reasonable limit on the number of
instructions per "tick." That might not matter much for a hypothetical
Python-based robot game, if it weren't designed to be interactive.
LambdaMOO still exists, incidentally! You might also be interested in a
python-implemented version of the main MOO core, the unfortunately
named POO: http://www.strout.net/python/poo/
I believe POO's "thread model" is much the same as I've described
above: inherently it's cooperative multitasking.

Incidentally, if you don't like the name POO, there's also MOOP at
moop.sourceforge.net. I don't know if MOOP is derived from POO, but
they have similar descriptions and aims, so I wouldn't be *too*
surprised.

Aug 11 '06 #12

li*****@gmail.com wrote:
You should take a look at stackless Python. It should do very nicely
for what you want. There is a good tutorial on it here:
http://members.verizon.net/olsongt/s...stackless.html
Not being intimately familiar with Stackless myself, I wonder, how
would it deal with a script that executed the line:

x = 10 ** 10 ** 10

My guess is that would cause a Stackless interpreter to block for a
long, long time, until it ran out of memory, but I'd like someone who
*knows* and doesn't have to guess to comment. :-)

Aug 11 '06 #13
Yannick wrote:
Thank you all for the detailled answers.

What I would like to achieve is something like:

# main loop
while True:
for robot in robots:
robot.start()
robot.join(0.2) # wait 200ms
if robot.is_active():
robot.stop()
# run all the game physics, pause, frame/rate, etc...

Unfortunately the stop() call doesn't exist in Python.

By using a generator I would make the assumption that every robot is
playing fair, and would yield often. But I cannot control this as
eventually robots would be coded by third parties.

Using Python scheduler would allow me to share time equally between
each robot, but then I would loose the ability to have a main thread
organizing everything.
I think the best way is to give each robot its own thread. That way the
interpreter will share time between each of the robots (whether or not
they sleep or yield) on a reasonably fair basis.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Aug 12 '06 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Benjamin Sher | last post by:
Dear friends: I would appreciate your help in installing SIP with QT support so that I can then install PyQT. My reason is that I would like to install a number of KDE applications that...
1
by: Neil Zanella | last post by:
Hello, What is the best way to install a python application under Unix. Since python modules are platform independent I would guess these should be placed under an application specific directory...
114
by: Maurice LING | last post by:
This may be a dumb thing to ask, but besides the penalty for dynamic typing, is there any other real reasons that Python is slower than Java? maurice
2
by: BrianS | last post by:
Hi, I'm trying to learn Python and wanted to play with Tkinter. I couldn't get it to work so I figured it would help if I installed the newest verison of Python. I downloaded the source,...
3
by: Michael Sparks | last post by:
Hi, I'm posting a link to this since I hope it's of interest to people here :) I've written up the talk I gave at ACCU Python UK on the Kamaelia Framework, and it's been published as a BBC...
8
by: Paul Cochrane | last post by:
Hi all, I've got an application that I'm writing that autogenerates python code which I then execute with exec(). I know that this is not the best way to run things, and I'm not 100% sure as to...
112
by: mystilleef | last post by:
Hello, What is the Pythonic way of implementing getters and setters. I've heard people say the use of accessors is not Pythonic. But why? And what is the alternative? I refrain from using them...
2
by: Jean-Paul Calderone | last post by:
On Mon, 16 Jun 2008 08:39:52 +1000, Ben Finney <bignose+hates-spam@benfinney.id.auwrote: Maybe. I'm no expert on Debian packaging. However, exarkun@boson:~$ ls -l...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.