How to use the greenlet.greenlet function in greenlet

To help you get started, we’ve selected a few greenlet examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github python-greenlet / greenlet / tests / test_throw.py View on Github external
except IndexError:
                return "caught"
            else:
                return "normal exit"

        def f2():
            main.switch("from f2")

        g1 = greenlet(f1)
        g2 = greenlet(f2, parent=g1)
        self.assertRaises(IndexError, g2.throw, IndexError)
        self.assertTrue(g2.dead)
        self.assertTrue(g1.dead)

        g1 = greenlet(f1)
        g2 = greenlet(f2, parent=g1)
        res = g1.switch()
        self.assertEqual(res, "f1 ready to catch")
        res = g2.throw(IndexError)
        self.assertEqual(res, "caught")
        self.assertTrue(g2.dead)
        self.assertTrue(g1.dead)

        g1 = greenlet(f1)
        g2 = greenlet(f2, parent=g1)
        res = g1.switch()
        self.assertEqual(res, "f1 ready to catch")
        res = g2.switch()
        self.assertEqual(res, "from f2")
        res = g2.throw(IndexError)
        self.assertEqual(res, "caught")
        self.assertTrue(g2.dead)
github ajdavis / GreenletProfiler / test / test_greenlet_profiler.py View on Github external
gr_main.switch()
            b()
            spin(1)

        def b():
            spin(5)
            gr_main.switch()
            c()
        
        def c():
            spin(7)
        
        GreenletProfiler.set_clock_type('cpu')
        GreenletProfiler.start(builtins=True)
        gr_main = greenlet.getcurrent()
        g = greenlet.greenlet(a)
        g.switch()
        spin(2)
        g.switch()
        spin(3)
        g.switch()
        self.assertFalse(g, 'greenlet not complete')
        GreenletProfiler.stop()

        ystats = GreenletProfiler.get_func_stats()

        # Check the stats for spin().
        spin_stat = find_func(ystats, 'spin')
        self.assertEqual(5, spin_stat.ncall)
        self.assertAlmostEqual(18 * self.spin_cost, spin_stat.ttot,
                               places=2, msg="spin()'s total time is wrong")
github lyonyang / blogs / Code / blogs-code / ConcurrentProgramming / ConcurrentCoroutine / greenlet_version.py View on Github external
def add1():
    num = 1
    for i in range(10000000):
        num *= i
        g2.switch()

def add2():
    num = 1
    for i in range(10000000):
        num *= i
        g1.switch()

start_time = time.time()
g1 = greenlet.greenlet(add1)
g2 = greenlet.greenlet(add2)
g1.switch()
end_time = time.time()
print(end_time - start_time)
github neovim / pynvim / pynvim / msgpack_rpc / session.py View on Github external
self._request_cb = request_cb
        self._notification_cb = notification_cb
        self._is_running = True
        self._setup_exception = None
        self._loop_thread = threading.current_thread()

        def on_setup():
            try:
                setup_cb()
            except Exception as e:
                self._setup_exception = e
                self.stop()

        if setup_cb:
            # Create a new greenlet to handle the setup function
            gr = greenlet.greenlet(on_setup)
            gr.switch()

        if self._setup_exception:
            error('Setup error: {}'.format(self._setup_exception))
            raise self._setup_exception

        # Process all pending requests and notifications
        while self._pending_messages:
            msg = self._pending_messages.popleft()
            getattr(self, '_on_{}'.format(msg[0]))(*msg[1:])
        self._async_session.run(self._on_request, self._on_notification)
        self._is_running = False
        self._request_cb = None
        self._notification_cb = None
        self._loop_thread = None
github katharosada / botchallenge / client / botchallenge / client.py View on Github external
def __init__(self, host, port):
        self.loop = asyncio.get_event_loop()
        self.host = host
        self.port = port
        self.network_greenlet = None
        self.protocol = None

        # Grab the current execution context as the robot greenlet
        self.robot_greenlet = greenlet.getcurrent()
        # Prepare to run the asyncio event loop in the network greenlet
        self.network_greenlet = greenlet(self._run_event_loop)
        # Start the asyncio event loop and switch to it (to connect)
        self.network_greenlet.switch()
github lucastx / propagator.py / propagator / util.py View on Github external
def callcc(f):
    saved = [greenlet.getcurrent()]

    def cont(val):
        if saved[0] == None:
            raise ContinuationError("one shot continuation called twice")
        else:
            return saved[0].switch(val)

    def new_cr():
        v = f(cont)
        return cont(v)

    value_cr = greenlet.greenlet(new_cr)
    value = value_cr.switch()
    saved[0] = None
    return value
github neovim / pynvim / neovim / client.py View on Github external
rv = self.request_cb(name, args)
                debug('greenlet %s completed, sending %s as response', gr, rv)
                reply_fn(rv)
            except Exception as e:
                if self.loop_running:
                    err_str = format_exc(5)
                    warn("error caught while processing call '%s %s': %s",
                         name,
                         args,
                         err_str)
                    reply_fn(err_str, error=True)
                    debug('sent "%s" as response', err_str)
            debug('greenlet %s is now dying...', gr)
            self.greenlets.remove(gr)

        gr = greenlet.greenlet(request_handler)
        debug('received rpc request, greenlet %s will handle it', gr)
        self.greenlets.add(gr)
        gr.switch()
github VOLTTRON / volttron / applications / pnnl / DemandResponseAgent / DemandResponse / Archive / DRAgent2.py View on Github external
def greenlet(self, *args, **kwargs):
            task = greenlet.greenlet(*args, **kwargs)
            self.tasks.append(task)
            current = greenlet.getcurrent()
            if current.parent is not None:
                task.parent = current.parent
            task.switch()
github neovim / pynvim / pynvim / msgpack_rpc / session.py View on Github external
def _on_notification(self, name, args):
        def handler():
            try:
                self._notification_cb(name, args)
                debug('greenlet %s finished executing', gr)
            except Exception:
                warn("error caught while processing notification '%s %s': %s",
                     name, args, format_exc())

            debug('greenlet %s is now dying...', gr)

        gr = greenlet.greenlet(handler)
        debug('received rpc notification, greenlet %s will handle it', gr)
        gr.switch()