Presentation on theme: "Programming Robots Python-Threading. Programming Robots Thread vs Threading Python offers two thread modules Thread: used up to now; including this."— Presentation transcript:
Programming Robots Thread vs Threading Python offers two thread modules Thread: used up to now; including this homework. start_new_thread(): simple mechanism that hides many details of running athread Locking: Threading: Thread class which we subclass and override run(). vlock = thread.allocate_lock() vlock.acquire()... vlock.release()
Programming Robots Program Paradigm: Create two robot objects. Subclass Thread and implement run(). Create two threads and start them Wait in the main thread until the two child threads are done. Avoid infinite loops that consume CPU cycles
Programming Robots Using Threading: The key here is to avoid having the thread constantly consuming CPU cycles by checking if it is time to do its thing. The threading.Event class will cause the thread that calls the threading.Event.wait() method to go to sleep. It will stay asleep until it is awoken by another thread calling the threading.Event.set() method. In order for the wait() method to do the correct thing in the future it is important to call threading.Event.clear().
Programming Robots Robot Methods: Wait: This method invokes the Event.wait() method and always returns False. Dflt: This method determines direction to to turn and returns True calling doRotate()
Programming Robots More Code: from myro import * from myRobot import * from random import Random import threading class WhirlingDervish (MyScribbler): myEvent = threading.Event() myLock = threading.Lock() direction = 1 def __init__(self,port,t=0,r=0): MyScribbler.__init__(self,port,t,r) # add additional behaviours here for this program only self.masterMethodsList['Wait'] = self.Wait self.masterMethodsList['dflt'] = self.dflt
Programming Robots def Wait(self): # instead of consuming CPU time this dervish goes to sleep print 'Waiting' WhirlingDervish.myEvent.wait() # upon waking up; it fails through to the default method return [False,self.T,self.R,self.move] def dflt(self): rotate = +1 if (WhirlingDervish.direction == -1): rotate = -1 # dflt always succeeds return [True,0,rotate,self.doRotate]
Programming Robots More Code def doRotate(self,t,r): global direction self.move(t,r) sleep(Random.random()*4.0) self.stop() WhirlingDervish.myLock.acquire() if (Random.random() < 0.5) : WhirlingDervish.direction = 1 else: WhirlingDervish.direction = -1 WhirlingDervish.myLock.release() WhirlingDervish.myEvent.set() WhirlingDervish.myEvent.clear()
Programming Robots Other threading Clases Event.set() wakes up all threads waiting on the same event. We work at a lower level – threading.Condition. In threading.Condition we use two methods – notify() and notifyAll(). NotifyAll() is just Event.set(). Notify() tells the thread manager to awaken one waiting thread, we don't know which.