def nodeFunction(self, myID, instrChannel, myChannel, lnChannel, rnChannel): print myID myState = False while True: todo = instrChannel.receive() stackless.schedule() if todo[0] == 'ret': myChannel.send(myState) elif todo[0] == 'set': if todo[1] == None: myState = myChannel.receive() else: myState = todo[1] elif todo[0] == 'shiftR': if myID % 2 == 0: rnChannel.send(myState) myState = myChannel.receive() else: tmp = myChannel.receive() rnChannel.send(myState) myState = tmp stackless.schedule()
def recv(self, size): start = time() while True: try: return self.ssl.recv(size) except (WantReadError, WantWriteError): schedule() if time() - start > 3: raise SocketTimeout('time out') continue except SysCallError, e: if e.args == (-1, 'Unexpected EOF'): return '' raise SocketError(e.args[0]) except SSLError, e: try: thirdarg = e.args[0][0][2] except IndexError: raise e else: if thirdarg == 'first num too large': schedule() if time() - start > 3: raise SocketTimeout('time out') continue raise
def runAction(self): # Here we define the main action, a repetition of the function self.action() while self.running: # Runs the action self.action() # Give other tasklets its turn stackless.schedule()
def MainLoop(self): t=time.time() while self.running: self.Tick() self.DrawFrame() T=t self.lastframetime=time.time()-t t=time.time() #FIXED FRAME RATE #block until the difference is made up while time.time()-t < (1.0/30)-self.lastframetime-(10.0/6000): pass #import agl #vsync=1 #swap = c_long(int(vsync)) #_agl_context=agl.aglGetCurrentContext() #agl.aglSetInteger(_agl_context, agl.AGL_SWAP_INTERVAL, byref(swap)) self.lastframetime=time.time()-T t=time.time() gfx.SwapBuffers() self.ProcessEvents() #print "mainloop schedule" stackless.schedule()
def poll(self, timeout=1): while self.running and (self.overlappedByID or self._sleepers): self._check_sleepers() numBytes = DWORD() completionKey = c_ulong() ovp = POINTER(OVERLAPPED)() ret = GetQueuedCompletionStatus(self.handle, byref(numBytes), byref(completionKey), byref(ovp), timeout) if not ovp and ret == 0: if GetLastError() == WAIT_TIMEOUT: stackless.schedule() continue if ovp.contents.taskletID in self.overlappedByID: #print ovp.contents.taskletID, " tasklet ID IN pool" c = self.overlappedByID[ovp.contents.taskletID] else: #print ovp.contents.taskletID, " tasklet ID NOT in pool" continue #print "sending data back to channel in ID", ovp.contents.taskletID c.send(numBytes) #print "sent data to channel in ID", ovp.contents.taskletID, numBytes self.UnregisterChannelObject(ovp.contents.taskletID) self.running = False
def die(self): self.actor.send_message(self.actor, 'You have just died!') self.actor.set_room('Test/Death/Death Room') stackless.schedule() self.actor.room.broadcast( '%s falls to the ground, dead!' % self.actor.action_description, self.actor)
def startwork( f ): while 1: buf = f.recv(10) print `buf` f.send( buf ) SL.schedule()
def send_stackless_activity(f, *a, **kw): """ This allows to launch a function in an async way. A Deferred is returned """ d= defer.Deferred() t= stackless.tasklet(_stackless_thread_channel.send) t((d, f, a, kw)) stackless.schedule() return d
def launch(func, params=[]): t1 = stackless.tasklet(func)(*params) tasklets[t1] = 'atom://localhost/' + func.__module__ + '/' + func.__name__ while t1.scheduled: stackless.schedule() sleep(0.01)
def action(self): visitor = self.ch.receive() self.visitors.append(visitor) if len(self.visitors) == self.count: self.santa.ch.send((self.kind, self.visitors)) self.visitors = [] stackless.schedule()
def connToServer (): global sockIndex #创建一个socket连接到127.0.0.1:5200,并发送内容 connMain = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connMain.connect(("127.0.0.1", 5201)) tCiphertext = tDataManage.textToCiphertext("get|"+ str(sockIndex)) connMain.send(tCiphertext) print sockIndex sockIndex = sockIndex + 1 while True: #等待主服务端返回子服务器的端口号,并去连接新的子服务器 tMainRev = connMain.recv(1024) ##连接子服务器 if tMainRev: print 'get main-server ciphertext:' + str(tMainRev) tText = tDataManage.ciphertextToText(tMainRev) print 'get main-server tText:' + str(tText) connSon = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connSon.connect(("127.0.0.1", int(tText))) # while True: # tSonRev = connSon.recv(1024) # if tSonRev: # print 'get son-server msg:' + str(tSonRev) # stackless.schedule() stackless.schedule()
def test_except_full(self): rlist = [] def f(): rlist.append('f') return 1/0 def g(): rlist.append('bg') stackless.schedule() rlist.append('ag') def h(): rlist.append('bh') stackless.schedule() rlist.append('ah') tg = stackless.tasklet(g)() tf = stackless.tasklet(f)() th = stackless.tasklet(h)() try: stackless.run() except ZeroDivisionError: rlist.append('E') stackless.schedule() stackless.schedule() assert rlist == "bg f E bh ag ah".split()
def test_except(self): rlist = [] def f(): rlist.append('f') return 1/0 def g(): rlist.append('bg') stackless.schedule() rlist.append('ag') def h(): rlist.append('bh') stackless.schedule() rlist.append('ah') tg = stackless.tasklet(g)() tf = stackless.tasklet(f)() th = stackless.tasklet(h)() try: stackless.run() # cheating, can't test for ZeroDivisionError except Exception as e: rlist.append('E') stackless.schedule() stackless.schedule() assert rlist == "bg f E bh ag ah".split()
def runSingle(self): """Execute the schedule list once, then return """ try: stackless.schedule() except: self.printException()
def sleep(self, delay=0): """Suspend the active tasklet for a specified amount of seconds If delay is zero (default) then the tasklet just blocks. Returns seconds passed since sleep was called. """ startTime = time.clock() when = startTime + delay if delay: try: try: chn = self.chnPool.pop() except IndexError: chn = stackless.channel() # could also allocate more channels for chnPool self.sleepers.append((when, chn)) chn.receive() finally: self.chnPool.append(chn) else: stackless.schedule() return time.clock() - startTime
def nodeFunction(self, myID, channels): print myID stackless.schedule() rCount = 0 sCount = 0 numOfNeighbors = len(channels) - 1 nCommTrack = [False for i in range(len(channels))] while True: if rCount < numOfNeighbors: for nodeNum in range(len(channels)): if not nodeNum == myID: if nCommTrack[nodeNum] == False: print myID, '- chan bal: ', nodeNum, channels[nodeNum].balance if not channels[nodeNum].balance == 0: print myID, '- receiving: ', nodeNum, channels[nodeNum].receive() rCount += 1 nCommTrack[nodeNum] = True if sCount < numOfNeighbors: print myID, '- sending' channels[myID].send(myID) sCount += 1 print myID, '- comm count:', rCount, sCount if rCount == numOfNeighbors: if sCount == numOfNeighbors: print myID, '- all done' break
def cap_thread(): for t, data in cap: d = data[54:] pos = d.find("\n") if pos > 0: print d[:pos] SL.schedule( )
def run(self): while 1: Url.run(self) secondsToWait = 3.0 endTime = time.time() + secondsToWait while time.time() < endTime: stackless.schedule()
def run(self, timeout = 100): n = c_ulong() key = c_ulong() pol = POINTER(OVERLAPPED)() while 1: key.value = 0 r = GetQueuedCompletionStatus( self.hiocp, byref(n), byref(key), byref(pol), timeout ) print r, pol, n, key, GetLastError() if r == 0: if( key.value > 0 ): t = pol.contents.Type sock = self.sockmap[key.value] if t == 3: sock.read_ch.send(0) self.close_socket(key.value) SL.schedule() continue t = pol.contents.Type sock = self.sockmap[key.value] if t == 1: if sock.is_server: sock.read_ch.send( 1 ) else: sock.read_ch.send( n.value ) elif t == 2: sock.write_ch.send( n.value ) elif t == 3: sock.read_ch.send( 1 ) SL.schedule()
def testRunnablesOrderAtKill(self): def Safe(items): try: items.append('start') stackless.schedule() except ValueError: items.append('caught') stackless.schedule() tasklet1 = stackless.tasklet(lambda: 1 / 0)() items = [] tasklet2 = stackless.tasklet(Safe)(items) tasklet2.run() assert 'start' == ','.join(items) tasklet3 = stackless.tasklet(lambda: 1 / 0)() tasklet2.remove() tasklet2.remove() tasklet2.raise_exception(ValueError) assert 'start,caught' == ','.join(items) assert tasklet1.alive assert not tasklet2.alive assert tasklet3.alive tasklet1.remove() tasklet1.kill() # Don't run tasklet3. tasklet3.kill() tasklet2.kill()
def testSendInsert(self): channel_obj = stackless.channel() self.assertEqual(None, channel_obj.queue) tasklet1 = stackless.tasklet(lambda: 1 / 0)() tasklet2 = stackless.tasklet(channel_obj.receive)() tasklet2.run() self.assertRaisesStr( RuntimeError, 'You cannot remove a blocked tasklet.', tasklet2.remove) # channel_obj.send inserts tasklet2 after current, and since tasklet1 was # after current, the insertion runs tasklet1 eventually, which triggers # the ZeroDivisionError, propagated to current (== main). self.assertRaises(ZeroDivisionError, channel_obj.send, 0) self.assertEqual(1, stackless.getruncount()) self.assertEqual(None, channel_obj.queue) channel_obj.preference = 1 # Prefer the sender. tasklet1 = stackless.tasklet(lambda: 1 / 0)() tasklet2 = stackless.tasklet(channel_obj.receive)() self.assertEqual(False, tasklet2.blocked) self.assertEqual(True, tasklet2.scheduled) tasklet2.run() self.assertEqual(True, tasklet2.blocked) self.assertEqual(True, tasklet2.scheduled) self.assertEqual(tasklet1, stackless.getcurrent().next) self.assertEqual(None, channel_obj.send(0)) self.assertEqual(tasklet1, stackless.getcurrent().next) self.assertEqual(tasklet2, stackless.current.prev) tasklet1.remove() stackless.schedule()
def rectest(nrec, lev=0): if self.verbose: print nrec, lev if lev < nrec: rectest(nrec, lev + 1) else: schedule()
def worker(ch, sec, message): while True: sec.send(ch) ch.receive() print message stackless.schedule() sleep.Sleep(random.randint(0, 3))
def rectest(verbose, nrec, lev=0): if verbose: print str(nrec), lev if lev < nrec: rectest(verbose, nrec, lev + 1) else: schedule()
def MainLoop(): while deadlines or reads or writes or stackless.runcount > 1: if stackless.runcount > 1: timeout = 0 elif deadlines: timeout = max(0, min(pair[0] for pair in deadlines) - time.time()) else: timeout = None read_fds, write_fds, _ = select.select(reads, writes, (), timeout) to_call = [] for fd in read_fds: if fd in reads: to_call.extend(reads.pop(fd)) for fd in write_fds: if fd in writes: to_call.extend(writes.pop(fd)) now = time.time() i = j = 0 for pair in deadlines: if now >= pair[0]: to_call.append(pair[1]) else: deadlines[j] = pair j += 1 del deadlines[j:] for tasklet in to_call: tasklet.insert() stackless.schedule()
def stackless_task(): global exit_now while not exit_now: try: request = stackless_queue.get(block=True, timeout=0.01) except Queue.Empty: stackless.schedule() continue seq, method, args, kwargs = request #print >> sys.__stderr__, "stackless_task", globals(), __main__.__dict__ #print >> sys.__stderr__, method, args, kwargs #print >> sys.__stderr__ type, value, tb = sys.exc_info() try: ret = method(*args, **kwargs) except: try: if hasattr(method, "im_self"): method.im_self.idb.gui.interaction(None, None) print_exception() rpc.response_queue.put((seq, None)) except: # Link didn't work, print same exception to __stderr__ traceback.print_exception(type, value, tb, file=sys.__stderr__) exit() else: continue rpc.response_queue.put((seq, ret)) stackless.schedule() exit_now = getattr(RemoteDebugger.__main__, "exit_now", False)
def test_simple_channel(self): output = [] def print_(*args): output.append(args) def Sending(channel): print_("sending") channel.send("foo") def Receiving(channel): print_("receiving") print_(channel.receive()) ch=stackless.channel() task=stackless.tasklet(Sending)(ch) # Note: the argument, schedule is taking is the value, # schedule returns, not the task that runs next #stackless.schedule(task) stackless.schedule() task2=stackless.tasklet(Receiving)(ch) #stackless.schedule(task2) stackless.schedule() stackless.run() assert output == [('sending',), ('receiving',), ('foo',)]
def run(self): # logic area run check loop and wait for incoming charges. #inturpt = False #while inturpt != True: signal = self.mySyn.receive() #print signal #print self.charge, self.threshold, self.thresholdUpdate() #self.age += 1 while signal: #print "index: %i age: %i" % (self.index, self.age) #self.age += 1 if signal == "s": print "waiting for charge signal..."; else: #print self.ntasklet.alive #print signal self.addCharge(signal) if self.charge >= self.threshold: self.age += 1 print str(self.index) + " Exceeded Treshold " + str(self.charge) + " " + self.nType out = self.outputCharge() self.outputSignal() if self.nType == "o": self.exportSignal(out); self.thresholdUpdate() self.resetCharge() self.outputAdd() stackless.schedule()
def __getitem__(self, key): if key in self.deleted: raise KeyError(key) try: return self.cache[key] except KeyError: pass while not self.cache_invalid_lock.acquire(0): schedule() try: if key in self.invalid: raise ReadConflictError(key) e = channel() self.queue.put((e, dbmget, (self.db, key), {})) errno, e = e.receive() if errno != 0: raise e o = loads(e) self.cache[key] = o finally: self.cache_invalid_lock.release() return o
def run(self, timeout = 100): n = c_ulong() key = c_ulong() pol = POINTER(OVERLAPPED)() while 1: key.value = 0 r = GetQueuedCompletionStatus( self.hiocp, byref(n), byref(key), byref(pol), c_ulong(timeout) ) print r, pol, n, key, GetLastError() if r == 0: if( key.value > 0 ): t = pol.contents.Type obj = self.objmap[key.value] if t == 4: obj.recv_ch.send( 0 ) self.close_socket(obj) SL.schedule() continue # 1 recv, 2 send, 3 accept, 4 connect, 5 read 6 write t = pol.contents.Type sock = self.objmap[key.value] if t == 1: if sock.is_server: sock.recv_ch.send( 1 ) else: sock.recv_ch.send( n.value ) elif t == 2: sock.send_ch.send( n.value ) elif t == 3: sock.recv_ch.send( 1 ) elif t == 4: sock.recv_ch.send(r) elif t == 5: sock.read_ch.send(n.value) SL.schedule()
def rectest(nrec, lev=0): if self.verbose: print nrec, lev if lev < nrec: rectest(nrec, lev+1) else: schedule()
def testRecursiveLambda(self): recurse = lambda self, next: \ next-1 and self(self, next-1) or (schedule(), 42)[1] pickle.loads(pickle.dumps(recurse)) self.run_pickled(recurse, recurse, 13)
def genoutertest(n, when): for i in geninnertest(n): if i == when: schedule() return i
def tick(): count = 0 while (1): print "tick: ", count count += 1 stackless.schedule()
def tupletest(n, when): for i in tuple(range(n)): if i == when: schedule() return i
def h(): rlist.append('hb') stackless.schedule() rlist.append('ha')
def counter(n, ch): for i in xrange(n): stackless.schedule() ch.send(n)
def task(val): value = stackless.schedule(val) assert value == val
def Loop(i): for x in range(3): stackless.schedule() print_("schedule", i)
def g(): rlist.append('g') stackless.schedule()
class Test_Stackless: def test_simple(self): rlist = [] def f(): rlist.append('f') def g(): rlist.append('g') stackless.schedule() def main(): rlist.append('m') cg = stackless.tasklet(g)() cf = stackless.tasklet(f)() stackless.run() rlist.append('m') main() assert stackless.getcurrent() is stackless.getmain() assert rlist == 'm g f m'.split() def test_with_channel(self): rlist = [] def f(outchan): for i in range(10): rlist.append('s%s' % i) outchan.send(i) outchan.send(-1) def g(inchan): while 1: val = inchan.receive() if val == -1: break rlist.append('r%s' % val) ch = stackless.channel() t1 = stackless.tasklet(f)(ch) t2 = stackless.tasklet(g)(ch) stackless.run() assert len(rlist) == 20 for i in range(10): (s,r), rlist = rlist[:2], rlist[2:] assert s == 's%s' % i assert r == 'r%s' % i def test_send_counter(self): import random numbers = range(20) random.shuffle(numbers) def counter(n, ch): for i in xrange(n): stackless.schedule() ch.send(n) ch = stackless.channel() for each in numbers: stackless.tasklet(counter)(each, ch) stackless.run() rlist = [] while ch.balance: rlist.append(ch.receive()) numbers.sort() assert rlist == numbers def test_receive_counter(self): import random numbers = range(20) random.shuffle(numbers) rlist = [] def counter(n, ch): for i in xrange(n): stackless.schedule() ch.receive() rlist.append(n) ch = stackless.channel() for each in numbers: stackless.tasklet(counter)(each, ch) stackless.run() while ch.balance: ch.send(None) numbers.sort() assert rlist == numbers def test_scheduling_cleanup(self): rlist = [] def f(): rlist.append('fb') stackless.schedule() rlist.append('fa') def g(): rlist.append('gb') stackless.schedule() rlist.append('ga') def h(): rlist.append('hb') stackless.schedule() rlist.append('ha') tf = stackless.tasklet(f)() tg = stackless.tasklet(g)() th = stackless.tasklet(h)() rlist.append('mb') stackless.run() rlist.append('ma') assert rlist == 'mb fb gb hb fa ga ha ma'.split() def test_except(self): rlist = [] def f(): rlist.append('f') return 1/0 def g(): rlist.append('bg') stackless.schedule() rlist.append('ag') def h(): rlist.append('bh') stackless.schedule() rlist.append('ah') tg = stackless.tasklet(g)() tf = stackless.tasklet(f)() th = stackless.tasklet(h)() try: stackless.run() # cheating, can't test for ZeroDivisionError except Exception, e: rlist.append('E') stackless.schedule() stackless.schedule() assert rlist == "bg f E bh ag ah".split()
def h(): rlist.append('bh') stackless.schedule() rlist.append('ah')
def counter(n, ch): for i in xrange(n): stackless.schedule() ch.receive() rlist.append(n)
def f(): rlist.append('fb') stackless.schedule() rlist.append('fa')
def MainLoop(): while True: # Exceptions (if any) in event handlers would propagate to here. # Argument: nonblocking: don't block if nothing available. event.loop(stackless.runcount > 1) stackless.schedule()
def _close(): while self.fileobject._sock == self: stackless.schedule() self._sock.close() del sockets[id(self)]
def send(self, data, flags=0): self.sendBuffer += data stackless.schedule() return len(data)
def _doStacklessSchedule(): stackless.schedule() TaskletMetrics.scheduled = 0
def enumeratetest(n, when): for i, ig in enumerate([None] * n): if i == when: schedule() return i
def dicttestiterkeys(n, when): for i in dict([(i, i) for i in range(n)]).iterkeys(): if i == when: schedule() return n
def listtest(n, when): for i in range(n): if i == when: schedule() return i
def xrangetest(n, when): for i in xrange(n): if i == when: schedule() return i
def __init__(self, testcase): testcase.started = True schedule()
def testRecursiveLambda(self): recurse = lambda self, next: next - 1 and self(self, next - 1) or (schedule(), 42)[1] # @IgnorePep8 self.loads(self.dumps(recurse)) self.run_pickled(recurse, recurse, 13)
def Threebie(): for i in xrange(3): print " Threebie (iteration %d/%d)" % (i + 1, 3) stackless.schedule()
def genschedinnertest(n, when): for i in range(n): if i == when: schedule() yield i
def respond(self, from_actor, msg): if not from_actor == self: cmd = 'say I will do nothing for you.' stackless.tasklet( CommandRegistry.dispatch)(cmd, self) stackless.schedule()
MyRequestHandler.requestChannel.send(replyChannel) result = replyChannel.receive() self.write(result) self.finish() class MyHttp(http.HTTPChannel): requestFactory = MyRequestHandler class MyHttpFactory(http.HTTPFactory): protocol = MyHttp if __name__ == "__main__": from twisted.internet import reactor channel = stackless.channel() cgiTasklet = Cgi("cgiTasklet-1", channel) server = Server() stackless.tasklet(cgiTasklet.execute)() stackless.tasklet(server.execute)(8000, channel) print "Web Server started" stackless.tasklet(tick)() print "entering main loop" while (stackless.getruncount() > 1): stackless.schedule()
def f(i): res.append('A_%s' % i) stackless.schedule() res.append('B_%s' % i)
def settest(n, when): for i in set(range(n)): if i == when: schedule() return i