Beispiel #1
0
def mainloop():
    tylog.info('Main loop begin.')
    stackless.tasklet(reactor.run)()
    reactor.callLater(0, stackless.schedule)
    stackless.run()
    tylog.info('Main loop over.')
    sys.exit(0)
    def lifecycle(self, t):
        # Initial state - unrun
        self.assert_(t.alive)
        self.assert_(t.scheduled)
        self.assertEquals(t.recursion_depth, 0)
        # allow hard switching
        t.set_ignore_nesting(1)
        
        # Run a little
        res = stackless.run(10)
        self.assertEquals(t, res)
        self.assert_(t.alive)
        self.assert_(t.paused)
        self.failIf(t.scheduled)
        self.assertEquals(t.recursion_depth, 1)

        # Push back onto queue
        t.insert()
        self.failIf(t.paused)
        self.assert_(t.scheduled)
        
        # Run to completion
        stackless.run()
        self.failIf(t.alive)
        self.failIf(t.scheduled)
        self.assertEquals(t.recursion_depth, 0)
Beispiel #3
0
    def TestMonkeyPatchUDP(address):
        install()
        try:

            def UDPServer(address):
                listenSocket = stdsocket.socket(AF_INET, SOCK_DGRAM)
                listenSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
                listenSocket.bind(address)
                print 'waiting to receive'
                rdata = ''
                while len(rdata) < 512:
                    data, address = listenSocket.recvfrom(4096)
                    print 'received', data, len(data)
                    rdata += data

            def UDPClient(address):
                clientSocket = stdsocket.socket(AF_INET, SOCK_DGRAM)
                print 'sending 512 byte packet'
                sentBytes = clientSocket.sendto('-' + '*' * 510 + '-', address)
                print 'sent 512 byte packet', sentBytes

            stackless.tasklet(UDPServer)(address)
            stackless.tasklet(UDPClient)(address)
            stackless.run()
        finally:
            uninstall()
    def _test_watchdog_priority(self, soft):
        self.awoken = 0
        def runner_func(recursive, start):
            if  recursive:
                stackless.tasklet(runner_func)(recursive-1, start)
            with stackless.atomic():
                stackless.run(2, soft=soft, totaltimeout=True, ignore_nesting=True)
                a = self.awoken
                self.awoken += 1
            if recursive == start:
                # we are the first watchdog
                self.assertEqual(a, 0) #the first to wake up
                self.done += 1 # we were interrupted
            t1.kill()
            t2.kill()

        def task():
            while True:
                for i in xrange(100):
                    i = i
                stackless.schedule()

        t1 = stackless.tasklet(task)()
        t2 = stackless.tasklet(task)()
        t3 = stackless.tasklet(runner_func)(3, 3)
        stackless.run()
        self.assertEqual(self.done, 2)
Beispiel #5
0
    def TestMonkeyPatchUDP(address):
        # replace the system socket with this module
        #oldSocket = sys.modules["socket"]
        #sys.modules["socket"] = __import__(__name__)
        install()
        try:
            def UDPServer(address):
                listenSocket = stdsocket.socket(AF_INET, SOCK_DGRAM)
                listenSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
                listenSocket.bind(address)

                # Apparently each call to recvfrom maps to an incoming
                # packet and if we only ask for part of that packet, the
                # rest is lost.  We really need a proper unittest suite
                # which tests this module against the normal socket
                # module.
                print "waiting to receive"
                data, address = listenSocket.recvfrom(256)
                print "received", data, len(data)
                if len(data) != 256:
                    raise StandardError("Unexpected UDP packet size")

            def UDPClient(address):
                clientSocket = stdsocket.socket(AF_INET, SOCK_DGRAM)
                # clientSocket.connect(address)
                print "sending 512 byte packet"
                sentBytes = clientSocket.sendto("-"+ ("*" * 510) +"-", address)
                print "sent 512 byte packet", sentBytes

            stackless.tasklet(UDPServer)(address)
            stackless.tasklet(UDPClient)(address)
            stackless.run()
        finally:
            #sys.modules["socket"] = oldSocket
            uninstall()
Beispiel #6
0
    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()
Beispiel #7
0
    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 TestMonkeyPatchUDP(address):
        # replace the system socket with this module
        install()
        try:
            def UDPServer(address):
                listenSocket = stdsocket.socket(AF_INET, SOCK_DGRAM)
                listenSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
                listenSocket.bind(address)

                # Apparently each call to recvfrom maps to an incoming
                # packet and if we only ask for part of that packet, the
                # rest is lost.  We really need a proper unittest suite
                # which tests this module against the normal socket
                # module.
                print "waiting to receive"
                rdata = ""
                while len(rdata) < 512:
                    data, address = listenSocket.recvfrom(4096)
                    print "received", data, len(data)
                    rdata += data

            def UDPClient(address):
                clientSocket = stdsocket.socket(AF_INET, SOCK_DGRAM)
                # clientSocket.connect(address)
                print "sending 512 byte packet"
                sentBytes = clientSocket.sendto("-"+ ("*" * 510) +"-", address)
                print "sent 512 byte packet", sentBytes

            stackless.tasklet(UDPServer)(address)
            stackless.tasklet(UDPClient)(address)
            stackless.run()
        finally:
            uninstall()
Beispiel #9
0
    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()
Beispiel #10
0
    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 testSocketIsManaged(self):
        """The goal of this test is to verify that the tasklet created to
        manage the socket, actually starts."""

        # Give the rpc module access to the 'tasklet' class as its stackless
        # module has been replaced with a mock object.
        rpc.stackless.tasklet = stackless.tasklet

        # Make a mock version of '_ManageSocket' we can tell has been called.
        def new_ManageSocket(self):
            new_ManageSocket.called = True
        new_ManageSocket.called = False

        # Inject it in a way where we restore the old version so that
        # subsequent tests are not clobbered by leakage.
        old_ManageSocket = rpc.EndPoint._ManageSocket
        rpc.EndPoint._ManageSocket = new_ManageSocket
        try:
            _socket = DummyClass()
            endpoint = rpc.EndPoint(_socket)
            self.failUnless(stackless.runcount == 2, "_ManageSocket was not launched in a tasklet")
            # Ensure the _ManageSocket tasklet starts.
            stackless.run()
        finally:
            rpc.EndPoint._ManageSocket = old_ManageSocket

        # Verify that the scheduler/tasklet state is correct.
        self.failUnless(stackless.runcount == 1, "The scheduler still contains tasklets")
        # Verify that the tasklet gets started.
        self.failUnless(new_ManageSocket.called, "The mock _ManageSocket function was not called")
Beispiel #12
0
def mainloop():
    if REACTOR_RUN_NORMAL:
        ftlog.info('Main loop begin. REACTOR_RUN_NORMAL')
        stackless.tasklet(reactor.run)()
        reactor.callLater(0, stackless.schedule)
        stackless.run()
        ftlog.info('Main loop over. REACTOR_RUN_NORMAL')
        return

    loopcount = 0  # 测试代码, 有时接到tcp消息, 却不处理, log也不出, 为何?
    r = reactor  # escape eclipse error
    r.startRunning()
    while r._started:
        try:
            while r._started:
                loopcount += 1
                if loopcount > 1000000000:
                    loopcount = 0
                if loopcount % 100 == 0:
                    ftlog.debug("Main loop 100!")
                # Advance simulation time in delayed event processors.
                r.runUntilCurrent()
                _schedule_reactor()
                t2 = r.timeout()
                t = r.running and t2
                r.doIteration(t)
                _schedule_reactor()
        except:
            ftlog.error("Main loop error!")
        else:
            ftlog.info('Main loop terminated.')
        finally:
            _schedule_reactor()
    ftlog.info('Main loop over.')
    sys.exit(0)
    def test_bind(self):
        t = stackless.tasklet()
        wr = weakref.ref(t)

        self.assertFalse(t.alive)
        self.assertIsNone(t.frame)
        self.assertEquals(t.nesting_level, 0)

        t.bind(None)  # must not change the tasklet

        self.assertFalse(t.alive)
        self.assertIsNone(t.frame)
        self.assertEquals(t.nesting_level, 0)

        t.bind(self.task)
        t.setup(False)

        stackless.run()
        self.assertFalse(t.scheduled)
        self.assertTrue(t.alive)
        if stackless.enable_softswitch(None):
            self.assertTrue(t.restorable)
        self.assertIsInstance(t.frame, types.FrameType)

        t.insert()
        stackless.run()

        # remove the tasklet. Must run the finally clause
        t = None
        self.assertIsNone(wr())  # tasklet has been deleted
        self.assertEqual(self.finally_run_count, 1)
    def switch(self, data=None):
        if not self._tasklet.scheduled:
            self._tasklet.insert()
            stackless.run()

        self._channel.send(data)
        return self._channel.receive()
Beispiel #15
0
    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',)]
Beispiel #16
0
    def lifecycle(self, t):
        # Initial state - unrun
        self.assertTrue(t.alive)
        self.assertTrue(t.scheduled)
        self.assertEqual(t.recursion_depth, 0)
        # allow hard switching
        t.set_ignore_nesting(1)

        softSwitching = stackless.enable_softswitch(0); stackless.enable_softswitch(softSwitching)
        
        # Run a little
        res = stackless.run(10)
        self.assertEqual(t, res)
        self.assertTrue(t.alive)
        self.assertTrue(t.paused)
        self.assertFalse(t.scheduled)
        self.assertEqual(t.recursion_depth, softSwitching and 1 or 2)

        # Push back onto queue
        t.insert()
        self.assertFalse(t.paused)
        self.assertTrue(t.scheduled)
        
        # Run to completion
        stackless.run()
        self.assertFalse(t.alive)
        self.assertFalse(t.scheduled)
        self.assertEqual(t.recursion_depth, 0)
Beispiel #17
0
def run_repl():
    import code
    def interact():
        w = open_window()
        code.InteractiveConsole(locals=globals()).interact()
        w.close()
    stackless.tasklet(interact)()
    stackless.run()
 def threadfunc():
     t = stackless.tasklet(taskletfunc)()
     t.run()
     e1.set()
     while not e2.is_set():
         stackless.run()
         time.sleep(0.001)
     e2.wait() #wait until we can die
Beispiel #19
0
 def _stackless_thread(self):
     """
     Starts the stackless loop in its own bg thread, so other things can
     happen
     """
     self._msgtasklet = stackless.tasklet(self.message_processor)()
     while True:
         stackless.run()
 def test_run_paused(self):
     s = stackless.tasklet(lambda: None)
     s.bind(args=())
     self.assertTrue(s.paused)
     with self.switch_trap:
         self.assertRaisesRegex(RuntimeError, "switch_trap", s.run)
     self.assertTrue(s.paused)
     stackless.run()
 def testScheduleRemove(self):
     #schedule remove doesn't work if it is the only tasklet running under watchdog
     def func(self):
         stackless.schedule_remove()
         self.fail("We shouldn't be here")
     stackless.run() #flush all runnables
     stackless.tasklet(func)(self)
     stackless.run()
Beispiel #22
0
 def mainloop(self):
     for j in range(2):
         for y in range(self.count):
             for x in range(self.count): 
                 self.pings[y*self.count+x].instchannel.send(0)
         stackless.run()
         self.channel.send(['print', None, None])
         stackless.run()
Beispiel #23
0
 def run(self):
     print("Server Starting Up.")
     self.connection_manager = ConnectionManager()
     print("Connection Manager Started")
     self.connection_manager.start_accepting_connections()
     print("Connection Manager is now Accepting New Connections")
     while True:
         self.connection_manager.manage_connections()
         stackless.run()
 def testCrash1(self):
     #we need a lost blocked tasklet here (print the ids for debugging)
     hex(id(self.BlockingReceive()))
     gc.collect() #so that there isn't any garbage
     stackless.run()
     def TaskletFunc(self):
         pass
     hex(id(self.TaskletWithDelAndCollect(TaskletFunc)(self)))
     stackless.run() #crash here
Beispiel #25
0
def a_main_tasklet():
    threadID = 2

    stackless.tasklet(ManageSleepingTasklets)(threadID)

    stackless.tasklet(looping_tasklet)(threadID, 1)

    print threadID, "runcount.1", stackless.getruncount()
    stackless.run()
Beispiel #26
0
def _runServiceById(sid, proto_func):
    ftlog.info("run service:", sid)
    _initProtocol(sid, proto_func)
    stackless.set_schedule_callback(_tasklet_schedule_cb)
    if REACTOR_RUN_NORMAL:
        mainloop()
        return
    stackless.tasklet(mainloop)()
    stackless.run()
 def test_inner_run_completes_first(self):
     """Test that the outer run() is indeed paused when the inner one completes"""
     def runner_func():
         stackless.run()
         self.assertTrue(stackless.main.paused)
         self.done += 1
     stackless.tasklet(runner_func)()
     stackless.run()
     self.assertEqual(self.done, 2)
Beispiel #28
0
def mainloop0():
	while True:
		try:
			stackless.run()
		except (SystemExit, KeyboardInterrupt):
			break
		except:
			print_exc(file=stderr)
			continue
Beispiel #29
0
def RunIt():
    stackless.run()
    from random import randint
    ev_num = 1000000
    EV = MakeEvent(1, 'hello')
    for i in xrange(ev_num):
        idx = i % 1
        #idx = randint(0, num-1)
        ch_list[idx].send(EV)
 def _testSetProfileOnTasklet4(self, t, tf):
     t.run()
     self.assertIsNone(t.trace_function)
     self.assertIsNone(t.profile_function)
     t.profile_function = tf
     stackless.run()
     self.assertIsNone(t.trace_function)
     self.assertIsNone(t.profile_function)
     self.assertGreater(self.tracecount, 0)
Beispiel #31
0
    def testSequence(self):
        def sender():
            self.c.send_sequence(xrange(10))
            self.c.close()
            # this needs to change, close does not wake up a receiver, we must pump it
            while self.c.closing and not self.c.closed:
                self.c.send(None)

        data = []
        def receiver():
            for i in self.c:
                data.append(i)
            #remove the extra "pump" nones at the end....
            while data[-1] is None:
                data.pop(-1)
            data.append(10)

        stackless.tasklet(sender)()
        stackless.tasklet(receiver)()
        stackless.run()
        self.assertEqual(data, range(11))
        self.assertTrue(self.c.closed)
def ring(args):
    global elements
    cycles = 0
    tokens = 1
    if len(args) > 0:
        cycles = int(args[0])
    if len(args) > 1:
        tokens = int(args[1])

    head = stackless.channel()
    this = head
    for i in range(elements - 1):
        next = stackless.channel()
        stackless.tasklet(element)(this, next)
        this = next

    stackless.tasklet(root)(cycles, tokens, this, head)

    try:
        stackless.run()
    except TaskletExit:
        pass
def do_permutations(n, th):
    ret = []
    s = magickSquare(n)
    r = get_permutations(n)
    threads = []
    for i in range(th):
        threads.append(Worker())
    stackless.run()
    x = 0
    for p in permutations(r, n):
        if x > (th - 1): x = 0
        threads[x].disbatch.send({'p': p, 's': s, 'n': n})
        x += 1
    for z in threads:
        z.disbatch.send(None)
    for z in threads:
        recv = z.results.receive()
        for y in recv:
            ret.append(y)
        z.disbatch.close()
        z.results.close()
    return ret
Beispiel #34
0
    def test_unbind_ok(self):
        if not stackless.enable_softswitch(None):
            # the test requires softswitching
            return
        t = stackless.tasklet(self.task)(False)
        wr = weakref.ref(t)

        # prepare a paused tasklet
        stackless.run()
        self.assertFalse(t.scheduled)
        self.assertTrue(t.alive)
        self.assertEqual(t.nesting_level, 0)
        self.assertIsInstance(t.frame, types.FrameType)

        t.bind(None)
        self.assertFalse(t.alive)
        self.assertIsNone(t.frame)

        # remove the tasklet. Must not run the finally clause
        t = None
        self.assertIsNone(wr())  # tasklet has been deleted
        self.assertEqual(self.finally_run_count, 0)
Beispiel #35
0
def startFlow(request, flow):
    print "startFlow"

    global flowcount
    #register the new flow.
    flowid = flowcount
    flow.flowid = flowid
    openflows[flowid] = flow
    flowcount += 1

    #start new microthread containing the flow.
    def flowRunner():
        lastresponse = flow.run(request)
        del openflows[flowid]
        flow.channel.send(lastresponse)

    stackless.tasklet(flowRunner)()

    print "startflow tasklet online"
    stackless.run()
    firstresponse = flow.channel.receive()
    print "startFlow END"
    return firstresponse
Beispiel #36
0
    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
Beispiel #37
0
    def test_cooperative(self):
        output = []

        def print_(*args):
            output.append(args)

        def Loop(i):
            for x in range(3):
                stackless.schedule()
                print_("schedule", i)

        stackless.tasklet(Loop)(1)
        stackless.tasklet(Loop)(2)
        stackless.run()

        assert output == [
            ('schedule', 1),
            ('schedule', 2),
            ('schedule', 1),
            ('schedule', 2),
            ('schedule', 1),
            ('schedule', 2),
        ]
    def test_pickle(self):
        # Run global
        t = pickle.loads(self.get_pickled_tasklet())
        t.insert()
        if is_soft():
            stackless.run()
        else:
            self.assertRaises(RuntimeError, stackless.run)

        # Run on tasklet
        t = pickle.loads(self.get_pickled_tasklet())
        t.insert()
        if is_soft():
            t.run()
        else:
            self.assertRaises(RuntimeError, t.run)
            return # enough crap

        # Run on watchdog
        t = pickle.loads(self.get_pickled_tasklet())
        t.insert()
        while stackless.runcount > 1:
            returned = stackless.run(100)
Beispiel #39
0
    def test_run_return(self):
        #if the main tasklet had previously gone into C stack recusion-based switch, stackless.run() would give
        #strange results
        #this would happen after, e.g. tasklet pickling and unpickling
        #note, the bug was hard to repro, most of the time, it didn't occur.
        t = pickle.loads(self.get_pickled_tasklet())

        def func():
            pass

        t = stackless.tasklet(func)
        t()
        r = stackless.run()
        self.assertEqual(r, None)
Beispiel #40
0
    def test_schedule_callback(self):
        res = []
        cb = []
        def schedule_cb(prev, next):
            cb.append((prev, next))

        stackless.set_schedule_callback(schedule_cb)
        def f(i):
            res.append('A_%s' % i)
            stackless.schedule()
            res.append('B_%s' % i)

        t1 = stackless.tasklet(f)(1)
        t2 = stackless.tasklet(f)(2)
        maintask = stackless.getmain()
        stackless.run()
        assert res == ['A_1', 'A_2', 'B_1', 'B_2']
        assert len(cb) == 5
        assert cb[0] == (maintask, t1)
        assert cb[1] == (t1, t2)
        assert cb[2] == (t2, t1)
        assert cb[3] == (t1, t2)
        assert cb[4] == (t2, maintask)
Beispiel #41
0
def entry():
    import sylphisexceptions
    global sde

    #sde = SDEThread()

    #global debugger
    #from Debugger import Debugger
    #debugger = Debugger()

    #global rpcs
    #rpcs = rpcserver.CRPCServer(('127.0.0.1', 8000))
    #rpcs.register_instance(debugger)

    #debugger.setIdleCall(rpcs.handle_request)
    #debugger.enable_trace()
    mthread.new("entry()", _entry)

    if 0:
        import profile
        print "profiling"
        p = profile.Profile()
        p.runcall(stackless.run)
        p.print_stats()
    else:
        retry = True
        while retry:
            try:
                stackless.run()
                retry = False
            except Exception, e:
                ## If there are more microthreads running
                ## don't terminate. Just print out the exception
                ## and continue scheduling
                if stackless.getruncount() <= 2:
                    retry = False
                traceback.print_exc()
    def TestMonkeyPatchUDP(address):
        # replace the system socket with this module
        #oldSocket = sys.modules["socket"]
        #sys.modules["socket"] = __import__(__name__)
        install()
        try:

            def UDPServer(address):
                listenSocket = stdsocket.socket(AF_INET, SOCK_DGRAM)
                listenSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
                listenSocket.bind(address)

                # Apparently each call to recvfrom maps to an incoming
                # packet and if we only ask for part of that packet, the
                # rest is lost.  We really need a proper unittest suite
                # which tests this module against the normal socket
                # module.
                print("waiting to receive")
                data, address = listenSocket.recvfrom(256)
                print("received", data, len(data))
                if len(data) != 256:
                    raise RuntimeError("Unexpected UDP packet size")

            def UDPClient(address):
                clientSocket = stdsocket.socket(AF_INET, SOCK_DGRAM)
                # clientSocket.connect(address)
                print("sending 512 byte packet")
                buffer = bytearray("-" + ("*" * 510) + "-", "utf-8")
                sentBytes = clientSocket.sendto(buffer, 0, address)
                print("sent 512 byte packet", sentBytes)

            stackless.tasklet(UDPServer)(address)
            stackless.tasklet(UDPClient)(address)
            stackless.run()
        finally:
            #sys.modules["socket"] = oldSocket
            uninstall()
    def testSig_schedule_remove(self):
        # schedule_remove(retval=stackless.current)
        done = []

        def f(self):
            tlet = stackless.current
            for result in self.checkSignatureNamedArgs(
                    stackless.schedule_remove, 0, None, "retval", tlet):
                self.assertIs(tlet, result)
            o = object()
            self.assertIs(o, stackless.schedule_remove(o))
            done.append(True)

        def g(tlet):
            while tlet.alive:
                tlet.insert()
                stackless.schedule()

        t = stackless.tasklet(f)(self)
        self.addCleanup(t.kill)
        t2 = stackless.tasklet(g)(t)
        self.addCleanup(t2.kill)
        stackless.run()
        self.assertListEqual([True], done)
Beispiel #44
0
 def tfunc():
     # thread func.  Create a tasklet, remove it, and send it to the master.
     # then wait for the tasklet to finish.
     try:
         c2 = stackless.channel()
         tasklets = []
         for callable in callables:
             def helper(callable):
                 try:
                     callable()
                 except:
                     c2.send_throw(*sys.exc_info())
                 else:
                     c2.send(None)
             t = stackless.tasklet(helper)(callable)
             t.remove()
             tasklets.append(t)
         c.send(tasklets)
     except:
         c.send_throw(*sys.exc_info())
     stackless.__reduce__()
     for callable in callables:
         c2.receive()
     stackless.run()  # drain the scheduler
Beispiel #45
0
    def testForeignThread_scheduled(self):
        theThread, t = self.create_thread_task()
        try:
            self.assertEqual(t.thread_id, theThread.ident)
            self.assertTrue(t.alive)
            self.assertFalse(t.paused)
            t.remove()
            self.assertTrue(t.paused)

            t.bind_thread()

            self.assertTrue(t.alive)
            self.assertTrue(t.paused)

            self.assertNotEqual(t.thread_id, theThread.ident)
            self.assertEqual(t.thread_id, thread.get_ident())
            t.insert()
            self.assertFalse(t.paused)

            stackless.run()
            self.assertTrue(self.taskletExecuted)
            self.assertFalse(t.alive)
        finally:
            theThread.join()
Beispiel #46
0
def mainloop():
    """主循环"""
    if REACTOR_RUN_NORMAL:
        ftlog.info('Main loop begin. REACTOR_RUN_NORMAL')
        stackless.tasklet(reactor.run)()
        reactor.callLater(0, stackless.schedule)
        stackless.run()
        ftlog.info('Main loop over. REACTOR_RUN_NORMAL')
        return

    loopcount = 0  # 测试代码, 有时接到tcp消息, 却不处理, log也不出, 为何?
    r = reactor  # escape eclipse error
    r.startRunning()
    while r._started:
        try:
            while r._started:
                loopcount += 1
                if loopcount > 1000000000:
                    loopcount = 0
                if loopcount % 100 == 0:
                    ftlog.debug("Main loop 100!")
                # Advance simulation time in delayed event processors.
                r.runUntilCurrent()
                _schedule_reactor()
                t2 = r.timeout()
                t = r.running and t2
                r.doIteration(t)
                _schedule_reactor()
        except:
            ftlog.error("Main loop error!")
        else:
            ftlog.info('Main loop terminated.')
        finally:
            _schedule_reactor()
    ftlog.info('Main loop over.')
    sys.exit(0)
    def autoschedule(self):
        while stackless.runcount > 1:
            try:
                returned = stackless.run(self.bytecodes, soft = self.softSchedule)

            except Exception, e:

                # Can't clear off exception easily...
                while stackless.runcount > 1:
                    stackless.current.next.kill()

                raise e

            else:
                self.schedule_cb(returned)
Beispiel #48
0
    def _test_watchdog_on_tasklet(self, soft):
        def runner_func():
            # run the watchdog long enough to start t1 and t2
            stackless.run(150,
                          soft=soft,
                          totaltimeout=True,
                          ignore_nesting=True)
            if stackless.getruncount():
                self.done += 1  # we were interrupted
            t1.kill()
            t2.kill()

        def task():
            while True:
                for i in range(500):
                    i = i
                stackless.schedule()

        t1 = stackless.tasklet(task)()
        t2 = stackless.tasklet(task)()
        t3 = stackless.tasklet(runner_func)()

        stackless.run()
        self.assertEqual(self.done, 2)
Beispiel #49
0
def testChannel():
    sl.tasklet(receiving_tasklet)()
    sl.tasklet(sending_tasklet)()
    sl.tasklet(another_tasklet)()
    print("------Recevie Send Another-----")
    sl.run()

    sl.tasklet(sending_tasklet)()
    sl.tasklet(another_tasklet)()
    print("------Send  Another-----")
    sl.run()

    sl.tasklet(another_tasklet)()
    print("------Another-----")
    sl.run()

    print("------Recevie-----")
    sl.tasklet(receiving_tasklet)()
    sl.run()
Beispiel #50
0
def Run():
    '''
    Use instead of stackless.run() in order.to allow Sleep and BeNice
    to work.  If this is not called and BeNice is used and RunNiceTasklets
    is not called or Sleep is used and CheckSleepingTasklets is not called,
    then any tasklets which call BeNice or Sleep respectively will block
    indefinitely as there will be nothing to wake them up.

    This function will exit when there are no remaining tasklets to run,
    whether being nice or sleeping.
    '''
    while yieldChannel.balance or len(
            sleepingTasklets) > 1 or stackless.runcount > 1:
        RunNiceTasklets()
        t = stackless.run(500000)
        if t is not None:
            print "*** Uncooperative tasklet", t, "detected ***"
            traceback.print_stack(t.frame)
            print "*** Uncooperative tasklet", t, "being sent exception ***"
            t.raise_exception(TimeoutException)
        CheckSleepingTasklets()
Beispiel #51
0
def Shutdown(exitprocs):
    def RunAll():
        stackless.getcurrent().block_trap = True
        for proc in exitprocs:
            try:
                proc()
            except Exception:
                import log
                log.LogException('exitproc ' + repr(proc), toAlertSvc=False)
                sys.exc_clear()

    if exitprocs:
        TaskletExt('Shutdown', RunAll)()
        intr = stackless.run(1000000)
        if intr:
            log.general.Log('ExitProcs interrupted at tasklet ' + repr(intr),
                            log.LGERR)
    GetTaskletDump(True)
    if len(tasklets):
        KillTasklets()
        GetTaskletDump(True)
Beispiel #52
0
    def _test_schedule_deeper(self, soft):
        # get rid of self.worker
        stackless.run()
        self.assertFalse(self.worker.alive)
        self.assertEqual(self.done, 1)
        self.assertListEqual([None], self.watchdog_list)

        tasklets = [None, None, None]  # watchdog1, watchdog2, worker

        def worker():
            self.assertListEqual(
                [tasklets[0], stackless.main, tasklets[0], tasklets[1]],
                self.watchdog_list)
            self.assertFalse(tasklets[1].scheduled)
            tasklets[1].insert()
            self.done += 1
            for i in range(100):
                for j in range(100):
                    dummy = i * j
            if soft:
                stackless.schedule()
            self.done += 1

        def watchdog2():
            tasklets[2] = stackless.tasklet(worker)()
            stackless.run()

        def watchdog1():
            tasklets[1] = stackless.tasklet(watchdog2)()
            victim = stackless.run(1000,
                                   soft=soft,
                                   ignore_nesting=True,
                                   totaltimeout=True)
            self.assertEqual(
                self.done, 2,
                "worker interrupted too early or to late, adapt timeout: %d" %
                self.done)
            if not soft:
                self.assertEqual(tasklets[2], victim)

        tasklets[0] = stackless.tasklet(watchdog1)()
        stackless.run()
        self.assertLessEqual([None], self.watchdog_list)
        stackless.run()
        # avoid a resource leak
        for t in tasklets:
            t.kill()
Beispiel #53
0
    def testWoodcutterAddStamina(self):

        random.seed(1)

        worldActor = SWorld()  # For debugging use
        world = worldActor.channel

        woodcutter = SWoodcutter(world,
                                 location=(32 * 6 + 16, 32 * 4 + 16),
                                 velocity=4,
                                 instanceName='Woodcutter',
                                 roamingRadius=200,
                                 stamina=0,
                                 maxStamina=10)

        SHome(world, location=(32 * 6, 32 * 3), instanceName='WoodcutterHome')

        world.send((None, 'START_SINGLE_TICK_TASKLET'))
        r = stackless.run()
        logging.info('End of Program, stackless.run() result = %s' % r)

        self.assertGreater(woodcutter.stamina, 0)
 def testAttr_balance(self):
     c = stackless.channel()
     self.assertIsInstance(c.balance, int)
     self.assertEqual(0, c.balance)
     t = stackless.tasklet(c.send)(None)
     stackless.run()
     self.assertEqual(1, c.balance)
     t2 = stackless.tasklet(c.send)(None)
     stackless.run()
     self.assertEqual(2, c.balance)
     t.kill()
     self.assertEqual(1, c.balance)
     t2.kill()
     self.assertEqual(0, c.balance)
     t = stackless.tasklet(c.receive)()
     stackless.run()
     self.assertEqual(-1, c.balance)
     t2 = stackless.tasklet(c.receive)()
     stackless.run()
     self.assertEqual(-2, c.balance)
     t.kill()
     self.assertEqual(-1, c.balance)
     t2.kill()
     self.assertEqual(0, c.balance)
Beispiel #55
0
    def testHomelessStarvation(self):

        random.seed(1)

        worldActor = SWorld()  # For debugging use
        world = worldActor.channel

        woodcutter = SWoodcutter(world,
                                 location=(100, 100),
                                 velocity=4,
                                 instanceName='Woodcutter',
                                 roamingRadius=200,
                                 stamina=10,
                                 maxStamina=10)

        world.send((None, 'START_TICK_TASKLET'))
        r = stackless.run()
        logging.info('End of Program, stackless.run() result = %s' % r)

        self.assertEqual('STARVATION', woodcutter.deathReason)
        self.assertFalse(worldActor.registeredActors)
        self.assertFalse(worldActor.aboutToBeKilledActors)
        self.assertFalse(worldActor.tickDisabledActors)
Beispiel #56
0
def main():
    random.seed(1)

    logging.getLogger().setLevel(logging.INFO)

    worldActor = SWorld(width=8, height=8, disableCollisionCheck=True)
    world = worldActor.channel

    client = SClient(world, 'Client', ('14.49.42.133', 3000)).channel

    SDisplayWindow(world, windowTitle='Falling Sun Client', client=client)

    logging.info('All actors initialized successfully.')
    logging.info('Starting the tick tasklet...')

    try:
        world.send((None, 'START_TICK_TASKLET'))
        r = stackless.run()
        assert r is None

    except KeyboardInterrupt:
        logging.info('Exit by KeyboardInterrupt')

    logging.info('End of Program')
Beispiel #57
0
    def testOneWoodcutterAndOneWood(self):
        '''
        logging.getLogger().setLevel(logging.DEBUG)
        logging.debug('Debug level logging enabled.')
        '''

        random.seed(1)

        world = SWorld(exitOnNoHarvestables=True).channel

        home = SHome(world,
                     location=(32 * 5, 32 * 5),
                     instanceName='WoodcutterHome')

        SWoodcutter(world,
                    location=(32 * 3 + 16, 32 * 3 + 16),
                    homeLocation=home.location,
                    velocity=4,
                    instanceName='Woodcutter',
                    roamingRadius=200,
                    stamina=10000,
                    maxStamina=10000,
                    intention='PATHFINDING_HARVESTABLE')

        tree = STree(world,
                     'WOOD',
                     location=(32 * 4, 32 * 3),
                     instanceName='Tree',
                     hitpoints=1)

        world.send((None, 'START_TICK_TASKLET'))
        r = stackless.run()
        logging.info('End of Program, stackless.run() result = %s' % r)

        self.assertEqual(0, tree.hitpoints)
        self.assertEqual('DEPLETED', tree.deathReason)
Beispiel #58
0
    def test1(self):
        "Test multiple monitors, from test/test_set_schedule_callback.py"

        fu = self.assertTrue
        n = 2

        mon1 = SchedulingMonitor()
        stackless.set_schedule_callback(mon1)
        v = 3
        for i in range(n):
            stackless.tasklet(stackless.test_cframe)(v)
        c1 = mon1.count
        fu(c1 == 0, "No callbacks before running")
        stackless.run()
        c1 = mon1.count
        fu(c1 >= n * v, "At least as may callbacks as many test_cframe calls")

        mon2 = SchedulingMonitor()
        stackless.set_schedule_callback(mon2)
        v = 5
        for i in range(n):
            stackless.tasklet(stackless.test_cframe)(v)
        stackless.run()
        c2 = mon2.count
        fu(c2 >= n * v, "At least as may callbacks as many test_cframe calls")
        fu(mon1.count == c1, "No calls to previous callback")
        fu(c2 > c1, "More test_cframe calls => more callbacks on second run")

        stackless.set_schedule_callback(None)
        v = 7
        for i in range(n):
            stackless.tasklet(stackless.test_cframe)(v)
        stackless.run()
        c1p = mon1.count
        c2p = mon2.count
        fu(c1p == c1, "No calls to previous callback after setting it to None")
        fu(c2p == c2, "No calls to previous callback after setting it to None")
Beispiel #59
0
 def main():
     rlist.append('m')
     cg = stackless.tasklet(g)()
     cf = stackless.tasklet(f)()
     stackless.run()
     rlist.append('m')
Beispiel #60
0
 def run_tasklets(self, run_for = 0):
     try:
         return stackless.run(run_for)
     except Exception:
         self.handle_run_error(sys.exc_info())