Python share CPU time?

Tim Chase python.list at tim.thechases.com
Wed Aug 9 14:56:59 EDT 2006


> 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







More information about the Python-list mailing list