Ejemplo n.º 1
0
 def __init__(self, value, num, boardchannel):
     self.value = value
     self.channel = stackless.channel()
     self.instchannel = stackless.channel()
     self.num = num
     self.boardchannel = boardchannel
     self.neighbors = []
Ejemplo n.º 2
0
 def Create(cls, *args, **kwargs):
     self = cls.__new__(cls, *args, **kwargs)
     self.__processingChannel = stackless.channel()
     self.__resultsChannel = stackless.channel()
     self.__tasklet = eg.Tasklet(self.ProcessingTask)(*args, **kwargs)
     self.__tasklet.run()
     return self
Ejemplo n.º 3
0
	def __init__(self, f, t, p ):
		
		self.sock = _realsocket_old(f, t, p)
		
		self.read_buffer_len = c_ulong( 64 )
		self.read_buffer = create_string_buffer(self.read_buffer_len.value)
		self.write_buffer = create_string_buffer(self.read_buffer_len.value)
		
		self.read_ch = SL.channel()
		self.write_ch = SL.channel()
		self.is_server = False

		self.bind_addr=("",0)

		self.send_len = c_ulong()
		self.recv_len = c_ulong()
		
		self.readol = OVERLAPPED()
		self.writeol = OVERLAPPED()

		self.init_readol()
		self.init_writeol()

		self.connected = False
		self.wasConnected  = False

		self.server_addr = None
		
		self.recv_wsabuf = WSABUF()
		self.send_wsabuf = WSABUF()
Ejemplo n.º 4
0
	def __init__(self, f=AF_INET, t=SOCK_STREAM, p=0, s=None ):
		
		
		#_socketobject_old.__init__(self,f, t, p, s)
		self._sock = _realsocket_old(f,t,p)
		
		om.create_object( self )
		self.recv_buffer =  create_string_buffer( 64 )
		self.send_buffer =  create_string_buffer( 64 )
		
		self.send_ch = SL.channel( )
		self.recv_ch = SL.channel( )

		self.is_server = False

		self.bind_addr=( "", 0 )

		self.send_len = c_ulong()
		self.recv_len = c_ulong()
		
		self.recvol = OVERLAPPED()
		self.sendol = OVERLAPPED()

		self.init_recvol()
		self.init_sendol()

		self.connected = False
		self.wasConnected  = False

		self.server_addr = None
		
		self.recv_wsabuf = WSABUF()
		self.send_wsabuf = WSABUF()
Ejemplo n.º 5
0
    def test_nested_pipe(self):
        dprint('tnp ==== 1')
        def pipe(X, Y):
            dprint('tnp_P ==== 1')
            foo = X.receive()
            dprint('tnp_P ==== 2')
            Y.send(foo)
            dprint('tnp_P ==== 3')

        def nest(X, Y):
            X2, Y2 = stackless.channel(), stackless.channel()
            t = stackless.tasklet(pipe)(X2, Y2)
            dprint('tnp_N ==== 1')
            X_Val = X.receive()
            dprint('tnp_N ==== 2')
            X2.send(X_Val)
            dprint('tnp_N ==== 3')
            Y2_Val = Y2.receive() 
            dprint('tnp_N ==== 4')
            Y.send(Y2_Val)
            dprint('tnp_N ==== 5')

        X, Y = stackless.channel(), stackless.channel()
        t1 = stackless.tasklet(nest)(X, Y)
        X.send(13)
        dprint('tnp ==== 2')
        res = Y.receive() 
        dprint('tnp ==== 3')
        assert res == 13
        if SHOW_STRANGE:
            raise Exception('force prints')
Ejemplo n.º 6
0
 def __init__(self):
     Abstract_actor.__init__(self)
     self.channel = stackless.channel()
     self.activate = stackless.channel()
     self.queue = deque([])
     self.channel.preference = -1
     self.callbacks = {}
     self.sync_parallel = []
Ejemplo n.º 7
0
 def __init__(self):
     self.channel = stackless.channel()
     self.activate = stackless.channel()
     self.aref = ''
     self.ref = False
     self.group = None
     self.queue = deque([])
     self.channel.preference = -1
     self.running = False
Ejemplo n.º 8
0
	def __init__(self, sock, addr):
		self.socket = sock
		self.address = addr
		self.pid = sock.fileno()
		self._rbuf = self._wbuf = ''
		self.read_channel = channel()
		self.write_channel = channel()
		self.writing = self.reading = None
		socket_map[self.pid] = proxy(self)
Ejemplo n.º 9
0
 def __init__(self, lockName = ''):
     self.name = lockName
     self.rchan = stackless.channel()
     self.wchan = stackless.channel()
     self.rchan.preference = self.wchan.preference = 0
     self.state = 0
     self.tasklets = []
     self.lockedWhen = None
     locks.Register(self)
Ejemplo n.º 10
0
    def test_simple_pipe(self):
        def pipe(X_in, X_out):
            foo = X_in.receive()
            X_out.send(foo)

        X, Y = stackless.channel(), stackless.channel()
        t = stackless.tasklet(pipe)(X, Y)
        stackless.run()
        X.send(42)
        assert Y.receive() == 42
Ejemplo n.º 11
0
 def __init__(self, lockName = 'noname'):
     self.name = lockName
     self.rchan = stackless.channel()
     self.wchan = stackless.channel()
     self.rchan.preference = self.wchan.preference = 1
     self.nWaiting = [0, 0]
     self.state = 0
     self.owning = []
     self.lockedWhen = None
     lockManager.Register(self)
Ejemplo n.º 12
0
def main():
    options, args = parser.parse_args()
    leftmost = stackless.channel()
    left, right = None, leftmost
    for i in xrange(options.num_tasklets):
        left, right = right, stackless.channel()
        stackless.tasklet(f)(left, right)
    right.send(0)
    x = leftmost.receive()
    print x
Ejemplo n.º 13
0
	def __init__(self):
		self._rbuf = ''
		self.headers = {}
		self.environ = {}
		self.content = []
		self.headers_set = []
		self.working_channel = None
		self.read_channel  = channel()
		self.write_channel = channel()
		self.write = self.content.append
		self.eof   = self.overflow = False
		self.handle_read = self.read4cache
Ejemplo n.º 14
0
 def __init__(self, sock):
     self.sock = sock
     self.accepting = False
     self.connected = False
     self.remote_addr = None
     self.fileobject = None
     self.read_channel = stackless.channel()
     self.write_channel = stackless.channel()
     self.accept_channel = None
     global sockets
     sockets[id(self)] = self
     runEventLoop()
Ejemplo n.º 15
0
 def nest(X, Y):
     X2, Y2 = stackless.channel(), stackless.channel()
     t = stackless.tasklet(pipe)(X2, Y2)
     dprint('tnp_N ==== 1')
     X_Val = X.receive()
     dprint('tnp_N ==== 2')
     X2.send(X_Val)
     dprint('tnp_N ==== 3')
     Y2_Val = Y2.receive() 
     dprint('tnp_N ==== 4')
     Y.send(Y2_Val)
     dprint('tnp_N ==== 5')
Ejemplo n.º 16
0
 def __init__(self, chainSize):
     self.chainSize = chainSize
     self.instrChannel = stackless.channel()
     self.chainChannel = [stackless.channel() for i in range(chainSize)]
     self.chain = [None for i in range(chainSize)]
     for nodeID in range(chainSize):
         self.chain[nodeID] = \
                 stackless.tasklet(
                     self.nodeFunction)(nodeID,
                     self.instrChannel,
                     self.chainChannel[nodeID],
                     self.chainChannel[(nodeID -1) % self.chainSize],
                     self.chainChannel[(nodeID + 1) % self.chainSize])
Ejemplo n.º 17
0
 def start(self):
     #errqueue = Queue()
     #statqueue = Queue()
     errlog = ErrLog('epoll_mp_srv')
     statlog = StatLog('epoll_mp_srv')
     errqueue = stackless.channel()
     statqueue = stackless.channel()
     stackless.tasklet(StackLessLog)(errqueue,errlog)
     stackless.tasklet(StackLessLog)(statqueue,statlog)
     stackless.run()
     handle_proc = MPConsumer(self.srvsocket,self.epoll,errqueue,statqueue)
     handle_proc.setDaemon(True)
     handle_proc.run()
Ejemplo n.º 18
0
 def __init__(self, numberOfNodes):
     self.numberOfNodes = numberOfNodes
     meshState = [False for i in range(self.numberOfNodes)]
     
     self.instChannel = stackless.channel()
     self.meshChannel = [stackless.channel() for \
                             i in range(self.numberOfNodes)]
     
     self.meshNode = [None for i in range(numberOfNodes)]
     
     for node in range(len(self.meshNode)):
         self.meshNode[node] = \
             stackless.tasklet(self.nodeFunction)(node, \
                     self.instChannel, self.meshChannel)
Ejemplo n.º 19
0
 def close(self):
     if hasattr(self, "db"):
         if self.changed or self.deleted:
             e = channel()
             self.queue.put((e, self._close_and_sync, (), {}))
             errno, e = e.receive()
             if errno != 0:
                 raise e
         else:
             e = channel()
             self.queue.put((e, self._close, (), {}))
             errno, e = e.receive()
             if errno != 0:
                 raise e
Ejemplo n.º 20
0
    def __init__(self, sock):
        # This is worth doing.  I was passing in an invalid socket which was
        # an instance of dispatcher and it was causing tasklet death.
        if not isinstance(sock, stdsocket.socket):
            raise StandardError("Invalid socket passed to dispatcher")
    
        asyncore.dispatcher.__init__(self, sock)

        self.acceptChannel = stackless.channel()
        self.connectChannel = stackless.channel()
        self.readChannel = stackless.channel()

        self.readBuffer = ''
        self.outBuffer = ''
Ejemplo n.º 21
0
def test_env(exported_names):
    from stackless import channel, tasklet, run
    inp, out = channel(), channel()
    remote_protocol = RemoteProtocol(inp.send, out.receive, exported_names)
    t = tasklet(remote_loop)(remote_protocol)
    
    #def send_trace(data):
    #    print "Sending %s" % (data,)
    #    out.send(data)

    #def receive_trace():
    #    data = inp.receive()
    #    print "Received %s" % (data,)
    #    return data
    return RemoteProtocol(out.send, inp.receive)
Ejemplo n.º 22
0
 def __init__(self, value=1):
     if value < 0:
         raise ValueError
     self._value = value
     self._chan = stackless.channel()
     set_channel_pref(self._chan)
     self._signaling = []
Ejemplo n.º 23
0
    def testNonBlockingReceive(self):
        ''' Test that when there is a waiting sender, we can receive without blocking with normal channel behaviour. '''
        originalValue = 1
    
        # Function to block when run in a tasklet.
        def f(testChannel, valueToSend):
            testChannel.send(valueToSend)

        # Get the tasklet blocked on the channel.
        channel = stackless.channel()
        tasklet = stackless.tasklet(f)(channel, originalValue)
        tasklet.run()

        # Make sure that the current tasklet cannot block when it tries to receive.  We do not want
        # to exit this test having clobbered the block trapping value, so we make sure we restore
        # it.
        oldBlockTrap = stackless.getcurrent().block_trap
        try:
            stackless.getcurrent().block_trap = True
            value = channel.receive()
        finally:
            stackless.getcurrent().block_trap = oldBlockTrap

        tasklet.kill()
        
        self.assertEqual(value, originalValue, "We received a value, but it was not the one we sent.  Completely unexpected.")
Ejemplo n.º 24
0
def sleep(secondsToWait):
    channel = stackless.channel()
    endTime = time.time() + secondsToWait
    sleepingTasklets.append((endTime, channel))
    sleepingTasklets.sort()
    # Block until we get sent an awakening notification.
    channel.receive()
Ejemplo n.º 25
0
def view(req_chan, search):
	running   = True
	cycle     = -1
	cache     = []
	resp_chan = stackless.channel()
	while running:
		msg = req_chan.receive()
		req = msg[0]

		if req == VIEW_BORROW_VIEW:
			resp = msg[1]
			req_cycle = msg[2]
			if req_cycle != cycle:
				cycle = req_cycle
				cache = []
				for (o, loc) in zip(offsets, search):
					nv = make_nv(o)
					loc.send((LOC_BORROW_INFO, resp_chan))
					agents = resp_chan.receive()
					merge_agents(cache, nv, agents)
					resp_chan.send(agents)
			resp.send(cache)
			cache = resp.receive()
		elif req == VIEW_SHUTDOWN:
			running = False
Ejemplo n.º 26
0
    def recv(self, byteCount, flags=0):
        if self.recvBuffer is None:
            self.recvBuffer = (WSABUF * 1)()
            self.recvBuffer[0].buf = ' ' * READ_BUFFER_SIZE
            self.recvBuffer[0].len = READ_BUFFER_SIZE

        # WARNING: For now, we cap the readable amount to size of the preallocated buffer.
        byteCount = min(byteCount, READ_BUFFER_SIZE)
    
        numberOfBytesRecvd = DWORD()
        flags = DWORD()
        ovRecv = OVERLAPPED()
        c = ovRecv.channel = stackless.channel()

        ret = WSARecv(self._socket, cast(self.recvBuffer, POINTER(WSABUF)), 1, byref(numberOfBytesRecvd), byref(flags), byref(ovRecv), 0)
        if ret != 0:
            err = WSAGetLastError()
            # The operation was successful and is currently in progress.  Ignore this error...
            if err != ERROR_IO_PENDING:
                raise WinError(err)    

        # Block until the overlapped operation completes.
        activeIO[self._socket] = c
        numberOfBytes = c.receive()
        return self.recvBuffer[0].buf[:numberOfBytes]
Ejemplo n.º 27
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', )]
Ejemplo n.º 28
0
 def sleep(self, seconds, channel=None):
     waketime = time.time() + seconds
     if channel is None:
         channel = stackless.channel()
     heappush(self._sleepers, (waketime, channel))
     self._check_running()
     channel.receive()
Ejemplo n.º 29
0
    def testNonBlockingSend(self):
        ''' Test that when there is a waiting receiver, we can send without blocking with normal channel behaviour. '''

        originalValue = 1
        receivedValues = []

        # Function to block when run in a tasklet.
        def f(testChannel):
            receivedValues.append(testChannel.receive())

        # Get the tasklet blocked on the channel.
        channel = stackless.channel()
        tasklet = stackless.tasklet(f)(channel)
        tasklet.run()

        # Make sure that the current tasklet cannot block when it tries to receive.  We do not want
        # to exit this test having clobbered the block trapping value, so we make sure we restore
        # it.
        oldBlockTrap = stackless.getcurrent().block_trap
        try:
            stackless.getcurrent().block_trap = True
            channel.send(originalValue)
        finally:
            stackless.getcurrent().block_trap = oldBlockTrap

        self.assertTrue(len(receivedValues) == 1 and receivedValues[0] == originalValue, "We sent a value, but it was not the one we received.  Completely unexpected.")
Ejemplo n.º 30
0
 def test_call_back(self):
     c = stackless.channel()
     def meh(*args):
         c.send(args)
     call_back(meh, (1,2,3))
     r = c.receive()
     self.assertEqual(r, (1, 2, 3))
Ejemplo n.º 31
0
def newJoinable(func, *args, **kw):
    def wrapper(selfTasklet, *args, **kw):
        exce = None
        result = None
        try:
            result = func(*args, **kw)
        except Exception as e:
            exce = sys.exc_info()

        try:
            if not selfTasklet.isTimedOut:
                stackless.channel.send(selfTasklet.doneChannel, (result, exce))
            else:
                log.general.Log(
                    "newJoinable timed out on function '" + str(func) +
                    "' with args '" + strx(args)[:2048] + "'", log.LGWARN)
        finally:
            exce = None

        return result

    ctx = ctxtfilter.sub('at (snip)', repr(func))
    ctx = blue.pyos.taskletTimer.GetCurrent().split('^')[-1] + '^' + ctx
    t = TaskletExtTimeoutable(ctx, wrapper)
    t.isTimedOut = False
    t.doneChannel = stackless.channel()
    t(t, *args, **kw)
    return t
Ejemplo n.º 32
0
 def __init__(self, name = 'noname'):
     self.name = name
     self.waiting = stackless.channel()
     self.waiting.preference = 1
     self.owning = None
     self.lockedWhen = None
     lockManager.Register(self)
Ejemplo n.º 33
0
    def testNonBlockingReceive(self):
        ''' Test that when there is a waiting sender, we can receive without blocking with normal channel behaviour. '''
        originalValue = 1

        # Function to block when run in a tasklet.
        def f(testChannel, valueToSend):
            testChannel.send(valueToSend)

        # Get the tasklet blocked on the channel.
        channel = stackless.channel()
        tasklet = stackless.tasklet(f)(channel, originalValue)
        tasklet.run()

        # Make sure that the current tasklet cannot block when it tries to receive.  We do not want
        # to exit this test having clobbered the block trapping value, so we make sure we restore
        # it.
        oldBlockTrap = stackless.getcurrent().block_trap
        try:
            stackless.getcurrent().block_trap = True
            value = channel.receive()
        finally:
            stackless.getcurrent().block_trap = oldBlockTrap

        tasklet.kill()

        self.assertEqual(value, originalValue, "We received a value, but it was not the one we sent.  Completely unexpected.")
Ejemplo n.º 34
0
 def WaitForInstance(self, instanceID):
     """
     Waits till the instance is loaded
     """
     if not self.IsInstanceLoaded(instanceID):
         self.instanceLoadedChannel[instanceID].append(stackless.channel())
         self.instanceLoadedChannel[instanceID][-1].receive()
Ejemplo n.º 35
0
    def acquire(self, blocking=1):
        if blocking:
            channel = stackless.channel()
            thread_id = stdstart_new_thread(_wait_for_lock, (self.stdlock, blocking, channel))
            return channel.receive()

        return self.stdlock.acquire(blocking)
Ejemplo n.º 36
0
 def __init__(self, actor_id, room):
     self.id = actor_id
     self.room = room
     self.last_message = None
     self.round_time = 0
     self.command_channel = stackless.channel()
     self.queued_commands = 0
Ejemplo n.º 37
0
    def testSendThrow(self):

        # subfunction in tasklet
        def bar():
            raise ValueError, (1,2,3)

        # Function to send the exception
        def f(testChannel):
            try:
                bar()
            except Exception:
                testChannel.send_throw(*sys.exc_info())

        # Get the tasklet blocked on the channel.
        channel = stackless.channel()
        tasklet = stackless.tasklet(f)(channel)
        tasklet.run()
        self.assertRaises(ValueError, channel.receive)

        tasklet = stackless.tasklet(f)(channel)
        tasklet.run()
        try:
            channel.receive()
        except ValueError:
            exc, val, tb = sys.exc_info()
            self.assertEqual(val.args, (1, 2, 3))

            # Check that the traceback is correct
            l = traceback.extract_tb(tb)
            self.assertEqual(l[-1][2], "bar")
 def testAttr_schedule_all(self):
     c = stackless.channel()
     self.assertIsInstance(c.schedule_all, int)
     self.assertEqual(c.schedule_all, 0)
     c.schedule_all = 1
     self.assertEqual(c.schedule_all, 1)
     c.schedule_all = False
     self.assertEqual(c.schedule_all, 0)
     c.schedule_all = -1
     self.assertEqual(c.schedule_all, 1)
     c.schedule_all = False
     self.assertEqual(c.schedule_all, 0)
     c.schedule_all = 2
     self.assertEqual(c.schedule_all, 1)
     c.schedule_all = False
     self.assertEqual(c.schedule_all, 0)
     c.schedule_all = True
     self.assertEqual(c.schedule_all, 1)
     self.assertRaisesRegex(TypeError, "must be set to a bool or integer",
                            setattr, c, "schedule_all", 2.5)
     if int is not long:
         self.assertRaisesRegex(
             TypeError, "preference must be set to a bool or integer",
             setattr, c, "schedule_all",
             9999999999999999999999999999999999999999999)
Ejemplo n.º 39
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
Ejemplo n.º 40
0
    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
Ejemplo n.º 41
0
    def testInterthreadCommunication(self):
        ''' Test that tasklets in different threads sending over channels to each other work. '''
        self.assertEqual(stackless.getruncount(), 1, "Leakage from other tests, with tasklets still in the scheduler.")

        commandChannel = stackless.channel()

        def master_func():
            commandChannel.send("ECHO 1")
            commandChannel.send("ECHO 2")
            commandChannel.send("ECHO 3")
            commandChannel.send("QUIT")

        def slave_func():
            while 1:
                command = commandChannel.receive()
                if command == "QUIT":
                    break

        def scheduler_run(tasklet_func):
            t = stackless.tasklet(tasklet_func)()
            while t.alive:
                stackless.run()

        thread = threading.Thread(target=scheduler_run, args=(master_func,))
        thread.start()

        scheduler_run(slave_func)
Ejemplo n.º 42
0
    def _send(self, data, flags):
        self._ensure_connected()

        channel = stackless.channel()
        channel.preference = 1 # Prefer the sender.
        self.writeQueue.append((channel, flags, data))
        return self.receive_with_timeout(channel)
Ejemplo n.º 43
0
    def __init__(self, config):
        self.config = config

        self.region = self.config.get("mud", {}).get("region", "us-east-1")

        email_config = self.config.get("email", {})
        self.endpoint = email_config.get("endpoint", None)
        self.use_ssl = email_config.get("useSsl", True)

        self.session = boto3.session.Session(region_name=self.region)
        self.ses = self.session.client('ses',
                                       endpoint_url=self.endpoint,
                                       use_ssl=self.use_ssl)

        self.mocked = email_config.get("mocked", False)

        self.extractor = URLExtract()
        self.extractor.update = self._update_tlds
        self.extractor_lock = Lock()

        self.url_re = re.compile(r'^(?P<type>.*://)?(?P<remainder>.*)$')
        self.html2text = HTML2Text()
        self.html2text.ignore_links = False
        self.html2text.ignore_images = False
        self.html2text.ignore_tables = False
        self.html2text.ignore_emphasis = False
        self.html2text_lock = Lock()

        self.in_channel = stackless.channel()

        stackless.tasklet(self._send_email_loop)()
Ejemplo n.º 44
0
def GetRemoteTasklets(callables):
    """Get a non-scheduled tasklet on a remote thread"""
    c = stackless.channel()

    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

    thread = threading.Thread(target=tfunc)
    thread.start()
    d = c.receive(), thread
    return d
Ejemplo n.º 45
0
    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
Ejemplo n.º 46
0
def tail(f, *args, **kwargs):
    def w(f, args, kwargs, result_ch):
        result_ch.send(f(*args, **kwargs))

    r = stackless.channel()
    stackless.tasklet(w)(f, args, kwargs, r)
    return r.receive()
Ejemplo n.º 47
0
    def test_new(self):
        c = stackless.channel()

        def foo():
            try:
                c.receive()
            except Exception as e:
                self.assertTrue(isinstance(e, IndexError))
                raise

        s = stackless.tasklet(foo)()
        self.assertEqual(s.frame, None)
        self.assertTrue(s.alive)

        # Test that the current "unhandled exception behaviour"
        # is invoked for the not-yet-running tasklet.

        def doit():
            self.throw(s, IndexError)

        if not self.pending:
            self.assertRaises(IndexError, doit)
        else:
            doit()
            self.assertRaises(IndexError, stackless.run)
Ejemplo n.º 48
0
def run(que, sharedDict):
    chan = stackless.channel()
    global mainTasklet
    mainTasklet = stackless.getcurrent()
    solSyst = SolarSystem(randint(3, 12), chan, sharedDict)
    stackless.tasklet(listenToQue)(que, chan)
    stackless.run()
Ejemplo n.º 49
0
    def testInterthreadCommunication(self):
        ''' Test that tasklets in different threads sending over channels to each other work. '''    
        self.assertEqual(stackless.getruncount(), 1, "Leakage from other tests, with tasklets still in the scheduler.")

        commandChannel = stackless.channel()

        def master_func():
            commandChannel.send("ECHO 1")
            commandChannel.send("ECHO 2")
            commandChannel.send("ECHO 3")
            commandChannel.send("QUIT")

        def slave_func():
            while 1:
                command = commandChannel.receive()
                if command == "QUIT":
                    break

        def scheduler_run(tasklet_func):
            t = stackless.tasklet(tasklet_func)()
            while t.alive:
                stackless.run()

        thread = threading.Thread(target=scheduler_run, args=(master_func,))
        thread.start()

        scheduler_run(slave_func)
Ejemplo n.º 50
0
    def __init__(self, name, circle):
        self.name = name
        self.circle = circle
        circle.append(self)
        self.channel = stackless.channel()

        stackless.tasklet(self.messageLoop)()
Ejemplo n.º 51
0
 def __init__(self,channelName=None):
     global channels
     self.channelName = channelName
     self.channel = stackless.channel()
     self.send = self.channel.send
     self.send_exception = self.channel.send_exception
     channels[self] = 1
Ejemplo n.º 52
0
def select(*channels, timeout=None, shuffle=False):
    """
    Timeout - wait for any message for this amount of milliseconds.
    Returns pair (channel, value) or None if timeout exceeded
    """
    if shuffle:
        random.shuffle(channels)

    if len(channels) == 0:
        if timeout is None:
            return None
        else:
            sleep(timeout)

    if len(channels) == 1 and timeout is None:
        value = channels[0].receive()
        return (channels[0], value)

    output = channel()

    tls = [tasklet(_proxy_task) for c in channels]
    tar = [c for c in channels]
    if timeout is not None:
        tls.append(tasklet(_timeout_task))
        tar.append(timeout)

    for tl, arg in zip(tls, tar):
        tl(arg, output, tls)

    return output.receive()
Ejemplo n.º 53
0
    def testNonBlockingSend(self):
        ''' Test that when there is a waiting receiver, we can send without blocking with normal channel behaviour. '''

        originalValue = 1
        receivedValues = []
    
        # Function to block when run in a tasklet.
        def f(testChannel):
            receivedValues.append(testChannel.receive())

        # Get the tasklet blocked on the channel.
        channel = stackless.channel()
        tasklet = stackless.tasklet(f)(channel)
        tasklet.run()

        # Make sure that the current tasklet cannot block when it tries to receive.  We do not want
        # to exit this test having clobbered the block trapping value, so we make sure we restore
        # it.
        oldBlockTrap = stackless.getcurrent().block_trap
        try:
            stackless.getcurrent().block_trap = True
            channel.send(originalValue)
        finally:
            stackless.getcurrent().block_trap = oldBlockTrap
        
        self.assertTrue(len(receivedValues) == 1 and receivedValues[0] == originalValue, "We sent a value, but it was not the one we received.  Completely unexpected.")
Ejemplo n.º 54
0
    def recv(self, byteCount, flags=0):
        if self.recvBuffer is None:
            self.recvBuffer = (WSABUF * 1)()
            self.recvBuffer[0].buf = ' ' * READ_BUFFER_SIZE
            self.recvBuffer[0].len = READ_BUFFER_SIZE

        # WARNING: For now, we cap the readable amount to size of the preallocated buffer.
        byteCount = min(byteCount, READ_BUFFER_SIZE)
    
        dwNumberOfBytes = DWORD()
        flags = DWORD()
        ovRecv = OVERLAPPED()
        opID = ovRecv.opID = self.__getnextopid()
        c = stackless.channel()
        c.preference = 0
        ovRecv.label = "recv"

        activeOps[(self._socket, opID)] = (c, ovRecv)

        ret = WSARecv(self._socket, cast(self.recvBuffer, POINTER(WSABUF)), 1, byref(dwNumberOfBytes), byref(flags), byref(ovRecv), 0)
        if ret == SOCKET_ERROR:            
            err = WSAGetLastError()
            # The operation was successful and is currently in progress.  Ignore this error...
            if err != ERROR_IO_PENDING:
                raise WinError(err)    

            # Block until the overlapped operation completes.
            numberOfBytes = c.receive()
        else:
            numberOfBytes = dwNumberOfBytes.value
            
        return self.recvBuffer[0].buf[:numberOfBytes]
Ejemplo n.º 55
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',)]
def Sleep(secondsToWait):
    channel = stackless.channel()
    endTime = time.time() + secondsToWait
    sleepingTasklets.append((endTime, channel))
    sleepingTasklets.sort()
    # Block until we get sent an awakening notification.
    channel.receive()
Ejemplo n.º 57
0
    def _send(self, data, flags):
        self._ensure_connected()

        channel = stackless.channel()
        channel.preference = 1 # Prefer the sender.
        self.writeQueue.append((channel, flags, data))
        return self.receive_with_timeout(channel)
Ejemplo n.º 58
0
 def PrepareComponent(self, sceneID, entityID, component):
     if entityID == session.charid:
         component.isClientPlayer = True
     if component.updater is None:
         component.updater = GameWorld.GWAnimation(None)
         component.updater.updateMode = 0
         component.updaterWaitingChannel = stackless.channel()
Ejemplo n.º 59
0
    def test0(self):
        "Simple monitored channel send from main tasklet."

        import stackless

        # create players
        chan = stackless.channel()
        main = stackless.getmain()  # implicit sender
        receiver = stackless.tasklet(lambda ch: ch.receive())
        receiver = receiver(chan)

        # send a value to a monitored channel
        chanMon = ChannelMonitor()
        stackless.set_channel_callback(chanMon)
        val = 42
        chan.send(val)
        stackless.set_channel_callback(None)

        # compare sent value with monitored one
        # found = chanMon.history[0][1].tempval
        # self.assertEqual(val, found) # FAILS - why?
        #
        # fails, because the value is moved from sender to receiver
        # also, I need to modify channels a little :-)
        # this one works, because I keep a copy of the value.
        #
        # print chanMon.history
        found = chanMon.history[0][-1]
        self.assertEqual(val, found)
Ejemplo n.º 60
0
    def connect(self, address):
        host, port = address

        self.bind(("0.0.0.0", 0))

        sa = sockaddr_in()
        sa.sin_family = AF_INET
        sa.sin_addr.s_addr = inet_addr(host)
        sa.sin_port = htons(port)

        bytesSent = DWORD(0)
        ovConnect = OVERLAPPED()
        opID = ovConnect.opID = self.__getnextopid()
        c = stackless.channel()
        c.preference = 0
        ovConnect.label = "connect"

        activeOps[(self._socket, opID)] = (c, ovConnect)

        ret = self.wsFnConnectEx(self._socket, sa, sizeof(sa), 0, 0, NULL, byref(ovConnect))
        if ret == FALSE:
            err = WSAGetLastError()
            # The operation was successful and is currently in progress.  Ignore this error...
            if err != ERROR_IO_PENDING:
                raise WinError()
            
            c.receive()