def test_greenlet_sockets(self):
        # Check that Pool gives two sockets to two greenlets
        try:
            import greenlet
            import gevent
        except ImportError:
            raise SkipTest('gevent not installed')

        from pymongo import thread_util_gevent

        cx_pool = pool.Pool(
            pair=(host,port),
            max_size=10,
            net_timeout=1000,
            conn_timeout=1000,
            use_ssl=False,
            thread_support_module=thread_util_gevent)

        socks = []

        def get_socket():
            cx_pool.start_request()
            socks.append(cx_pool.get_socket())

        looplet([
            greenlet.greenlet(get_socket),
            greenlet.greenlet(get_socket),
        ])

        self.assertEqual(2, len(socks))
        self.assertNotEqual(socks[0], socks[1])
Beispiel #2
0
def spawn_raw(function, *args, **kwargs):
    """
    Create a new :class:`greenlet.greenlet` object and schedule it to
    run ``function(*args, **kwargs)``.

    This returns a raw :class:`~greenlet.greenlet` which does not have all the useful
    methods that :class:`gevent.Greenlet` has. Typically, applications
    should prefer :func:`~gevent.spawn`, but this method may
    occasionally be useful as an optimization if there are many
    greenlets involved.

    .. versionchanged:: 1.1rc2
        Accept keyword arguments for ``function`` as previously (incorrectly)
        documented. Note that this may incur an additional expense.

    .. versionchanged:: 1.1a3
        Verify that ``function`` is callable, raising a TypeError if not. Previously,
        the spawned greenlet would have failed the first time it was switched to.
    """
    if not callable(function):
        raise TypeError("function must be callable")
    hub = get_hub()

    # The callback class object that we use to run this doesn't
    # accept kwargs (and those objects are heavily used, as well as being
    # implemented twice in core.ppyx and corecffi.py) so do it with a partial
    if kwargs:
        function = _functools_partial(function, *args, **kwargs)
        g = greenlet(function, hub)
        hub.loop.run_callback(g.switch)
    else:
        g = greenlet(function, hub)
        hub.loop.run_callback(g.switch, *args)
    return g
Beispiel #3
0
    def test_set_locale_is_per_greenlet_with_no_effect_on_other_greenlets(self):
        fa_record = []

        def record_greenlet_locale_fa():
            jdatetime.set_locale('fa_IR')
            nl_greenlet.switch()
            fa_record.append(jdatetime.get_locale())
            nl_greenlet.switch()

        nl_record = []

        def record_greenlet_locale_nl():
            jdatetime.set_locale('nl_NL')
            fa_greenlet.switch()
            nl_record.append(jdatetime.get_locale())
            fa_greenlet.switch()

        fa_greenlet = greenlet.greenlet(record_greenlet_locale_fa)
        nl_greenlet = greenlet.greenlet(record_greenlet_locale_nl)
        fa_greenlet.switch()

        self.assertEqual(1, len(fa_record))
        self.assertEqual('fa_IR', fa_record[0])
        self.assertEqual(1, len(nl_record))
        self.assertEqual('nl_NL', nl_record[0])
    def test_does_not_timeout_if_notified(self):
        def run_1(frozen):
            self.states.append(1)
            with self.lock:
                self.states.append(2)
                self.condition.wait(5)
                self.states.append(5)

            frozen.tick(delta=timedelta(seconds=90))

            self.ioloop.add_callback(self.ioloop.stop)
            greenlet.getcurrent().parent.switch()
            raise Exception

        def run_2():
            self.states.append(3)
            with self.lock:
                self.condition.notify_all()
            self.states.append(4)
            greenlet.getcurrent().parent.switch()

        green_1 = greenlet.greenlet(run_1)
        green_2 = greenlet.greenlet(run_2)

        with freezegun.freeze_time('12:00') as frozen:
            self.ioloop.add_callback(partial(green_1.switch, frozen))
            self.ioloop.add_callback(green_2.switch)
            self.ioloop.start()

        self.assertState(5)
Beispiel #5
0
    def method(self, *args, **kwargs):
        #loop = self.get_io_loop()
        loop = ioloop.IOLoop.current()
        callback = kwargs.pop('callback', None)

        if callback:
            if not callable(callback):
                raise callback_type_error
            future = None
        else:
            future = TracebackFuture()

        def call_method():
            # Runs on child greenlet.
            try:
                result = sync_method(self, *args, **kwargs)    #   用fun传对象调用方法
                if callback:
                    # Schedule callback(result, None) on main greenlet.
                    loop.add_callback(functools.partial(
                        callback, result, None))
                else:
                    # Schedule future to be resolved on main greenlet.
                    loop.add_callback(functools.partial(
                        future.set_result, result))
            except Exception as e:
                if callback:
                    loop.add_callback(functools.partial(
                        callback, None, e))
                else:
                    loop.add_callback(functools.partial(
                        future.set_exc_info, sys.exc_info()))

        # Start running the operation on a greenlet.
        greenlet.greenlet(call_method).switch()
        return future
    def test_notifies_after_timeout(self):
        def run_1():
            self.states.append(1)
            with self.lock:
                self.states.append(2)
                self.condition.wait(5)
                self.states.append(5)
                self.ioloop.add_callback(self.ioloop.stop)

        def run_2(frozen):
            self.states.append(3)
            # the point of doing this as a timeout instead of a straight
            # callback is the order in which it would get called if the other
            # would resume
            iotimeout = time.time() + 2
            self.ioloop.add_timeout(iotimeout, greenlet.getcurrent().switch)
            frozen.tick(delta=timedelta(seconds=4))
            greenlet.getcurrent().parent.switch()
            self.states.append(4)
            frozen.tick(delta=timedelta(seconds=2))
            greenlet.getcurrent().parent.switch()

        green_1 = greenlet.greenlet(run_1)
        green_2 = greenlet.greenlet(run_2)

        with freezegun.freeze_time('12:00') as frozen:
            self.ioloop.add_callback(green_1.switch)
            self.ioloop.add_callback(partial(green_2.switch, frozen))
            self.ioloop.start()

        self.assertState(5)
    def test_notify_all_is_queue(self):
        def run_1():
            self.states.append(1)
            with self.lock:
                self.states.append(2)
                self.condition.wait()
                self.states.append(8)

        def run_2():
            self.states.append(3)
            with self.lock:
                self.states.append(4)
                self.condition.wait()
                self.states.append(9)
                self.ioloop.add_callback(self.ioloop.stop)

        def run_3():
            self.states.append(5)
            with self.lock:
                self.states.append(6)
                self.condition.notify_all()
                self.states.append(7)

        green_1 = greenlet.greenlet(run_1)
        green_2 = greenlet.greenlet(run_2)
        green_3 = greenlet.greenlet(run_3)

        self.ioloop.add_callback(green_1.switch)
        self.ioloop.add_callback(green_2.switch)
        self.ioloop.add_callback(green_3.switch)
        self.ioloop.start()

        self.assertState(9)
    def test_acquire_release(self):
        def run_1():
            self.states.append(1)
            self.lock.acquire()
            self.states.append(2)
            greenlet.getcurrent().parent.switch()
            self.states.append(4)
            self.lock.release()
            self.states.append(5)

        def run_2():
            self.states.append(3)
            self.lock.acquire()
            self.states.append(6)
            self.ioloop.add_callback(self.ioloop.stop)

        green_1 = greenlet.greenlet(run_1)
        green_2 = greenlet.greenlet(run_2)

        self.ioloop.add_callback(green_1.switch)
        self.ioloop.add_callback(green_2.switch)
        self.ioloop.add_callback(green_1.switch)
        self.ioloop.start()

        self.assertState(6)
    def test_greenlet_sockets(self):
        # Check that Pool gives two sockets to two greenlets
        try:
            import greenlet
        except ImportError:
            raise SkipTest('greenlet not installed')

        cx_pool = pool.GreenletPool(
            pair=(host,port),
            max_size=10,
            net_timeout=1000,
            conn_timeout=1000,
            use_ssl=False
        )

        socks = []

        def get_socket():
            cx_pool.start_request()
            socks.append(cx_pool.get_socket())

        looplet([
            greenlet.greenlet(get_socket),
            greenlet.greenlet(get_socket),
        ])

        self.assertEqual(2, len(socks))
        self.assertNotEqual(socks[0], socks[1])
Beispiel #10
0
 def test_parent_return_failure(self):
     # No run causes AttributeError on switch
     g1 = greenlet()
     # Greenlet that implicitly switches to parent
     g2 = greenlet(lambda: None, parent=g1)
     # AttributeError should propagate to us, no fatal errors
     self.assertRaises(AttributeError, g2.switch)
Beispiel #11
0
    def test_REST_post_triggers_ws_multicast__topo_diff(self):

        class NS_test(BaseNamespace):

            def on_diff_commit__topo(self, *data):
                greenlet.getcurrent().data = data
                raise KeyboardInterrupt()  # TODO: cleanup: properly close socket

        test_label = neo4j_test_util.rand_label()
        n, n_id = util.generate_random_node_dict(test_label)
        topo_diff = Topo_Diff(node_set_add=[n])

        def c_0():

            with RZ_websocket(namespace=NS_test) as (sock, _):
                c1_t.switch()  # allow peer to POST
                sock.wait(8)  # allow self to receive

        def c_1():
            data = json.dumps({'topo_diff': topo_diff.to_json_dict()})
            req = Request(url='http://rhizi.local:8080/graph/diff-commit-topo',
                                  data=data,
                                  headers={'Content-Type': 'application/json'})

            f = urlopen(req)
            f.close()
            c0_t.switch()

        c0_t = greenlet(c_0)
        c0_t.data = None
        c1_t = greenlet(c_1)
        c0_t.switch()

        self.assertTrue(None != c0_t.data)
        self.assertEqual(2, len(c1_t.data))
    def test_pool_with_greenlets(self):
        try:
            from greenlet import greenlet
        except ImportError:
            raise SkipTest()

        c = get_connection()
        c.test.test.find_one()
        c.end_request()
        self.assertEqual(1, len(c._Connection__pool.sockets))
        a_sock = c._Connection__pool.sockets[0]

        def loop(name, pipe):
            c.test.test.find_one()
            self.assertEqual(0, len(c._Connection__pool.sockets))
            greenlet.getcurrent().parent.switch()
            c.end_request()
            pipe.append(c._Connection__pool.sockets[-1])

        ga1 = []
        ga2 = []

        g1 = greenlet(loop)
        g2 = greenlet(loop)

        g1.switch('g1', ga1)
        g2.switch('g2', ga2)
        g1.switch()
        g2.switch()

        b_sock = ga1[0]
        c_sock = ga2[0]
        self.assert_(a_sock is b_sock)
        self.assert_(a_sock is not c_sock)
        self.assert_(b_sock is not c_sock)
Beispiel #13
0
 def f():
     try:
         raise ValueError('fun')
     except:
         exc_info = sys.exc_info()
         greenlet(h).switch()
         assert exc_info == sys.exc_info()
Beispiel #14
0
    def handle(self, *args, **options):
        """f = FacebookFriendLike(user_id=10, friend_fid=5454,app_name='fo',
            facebook_id=4535,
            created_time='2011-10-24 11:40:52',
            release_date=None,
            category='fdfd',
            name='yoman',
            num_likes=5454,
            page_url='www.goel.com'
        )
        for i in xrange(10):
            flist =[f]*1000
        #for fr in flist:
        #    fr.save()
            insert_many(flist)
        self.stdout.write("Done")"""
        from greenlet import greenlet
        def test1():
            print 12
            gr2.switch()
            print 34

        def test2():
            print 56
            gr1.switch()
            print 78
        gr1 = greenlet(test1)
        gr2 = greenlet(test2)
        gr1.switch()
Beispiel #15
0
def run(loop):
    try:
        import tornado.ioloop
        import tornado.gen
    except ImportError:
        pass
    else:
        if isinstance(loop, tornado.ioloop.IOLoop):
            local.make_coroutine = tornado.gen.coroutine
            local.schedule = lambda x: x
            local.main = greenlet(loop.start)
            return local.main.switch()

    try:
        import asyncio
    except ImportError:
        pass
    else:
        if isinstance(loop, asyncio.AbstractEventLoop):
            local.make_coroutine = asyncio.coroutine
            local.schedule = loop.create_task
            local.main = greenlet(loop.run_forever)
            return local.main.switch()

    raise ValueError('Invalid event loop provided')
def test_greenlet_context():
    values = []
    store_1 = Store()
    store_2 = Store()
    def context_1():
        try:
            s = get_current_store()
        except ContextError:
            values.append('error')
        else:
            values.append(s)
        with store_context(store_1):
            values.append(get_current_store())
            greenlet_2.switch()
            values.append(get_current_store())
        try:
            s = get_current_store()
        except ContextError:
            values.append('error')
        else:
            values.append(s)
    def context_2():
        try:
            s = get_current_store()
        except ContextError:
            values.append('error')
        else:
            values.append(s)
        with store_context(store_2):
            values.append(get_current_store())
            greenlet_1.switch()
    greenlet_1 = greenlet.greenlet(context_1)
    greenlet_2 = greenlet.greenlet(context_2)
    greenlet_1.switch()
    assert values == ['error', store_1, 'error', store_2, store_1, 'error']
Beispiel #17
0
    def test_del_on_child_greenlet(self):
        if tornado_version < (4, 0, 0, 0):
            raise SkipTest("Tornado 3")

        # Since __del__ can happen on any greenlet, cursor must be
        # prepared to close itself correctly on main or a child.
        client, server = self.client_server(auto_ismaster=True)
        self.cursor = client.test.collection.find()

        future = self.cursor.fetch_next
        request = yield self.run_thread(server.receives, OpQuery)
        request.replies({'_id': 1}, cursor_id=123)
        yield future  # Complete the first fetch.

        def f():
            # Last ref, should trigger __del__ immediately in CPython and
            # allow eventual __del__ in PyPy.
            del self.cursor

        greenlet.greenlet(f).switch()

        # Let the event loop iterate once more to clear its references to
        # callbacks, allowing the cursor to be freed.
        yield self.pause(0)
        if 'PyPy' in sys.version:
            gc.collect()

        yield self.run_thread(server.receives, OpKillCursors)
Beispiel #18
0
 def f():
     try:
         raise ValueError('fun')
     except:
         exc_info = sys.exc_info()
         greenlet(h).switch()
         self.assertEqual(exc_info, sys.exc_info())
Beispiel #19
0
 def worker():
     # main and additional *finished* greenlets
     ll = greenlet.getcurrent().ll = []
     def additional():
         ll.append(greenlet.getcurrent())
     for i in range(2):
         greenlet.greenlet(additional).switch()
     gg.append(weakref.ref(greenlet.getcurrent()))
Beispiel #20
0
 def run_task(self, task, *a):
     try:
         if isinstance(task, greenlet):
             task.switch(*a)
         else:
             greenlet(task).switch(*a)
     except Exception, e:
         self.log.warn('Exception leaked back to main loop', exc_info=e)
Beispiel #21
0
    def test_stack_context(self):
        # See http://www.tornadoweb.org/documentation/stack_context.html
        # MotorPool.get_socket can block waiting for a callback in another
        # context to return a socket. We verify MotorPool's stack-context
        # handling by testing that exceptions raised in get_socket's
        # continuation are caught in get_socket's stack context, not
        # return_socket's.

        loop = self.io_loop
        history = []
        cx = yield self.motor_client(max_concurrent=1)

        # Open a socket
        yield cx.pymongo_test.test_collection.find_one()

        pool = cx._get_pools()[0]
        self.assertEqual(1, len(pool.sockets))
        sock_info = pool.get_socket()

        main_gr = greenlet.getcurrent()

        def catch_get_sock_exc(exc_type, exc_value, exc_traceback):
            history.extend(['get_sock_exc', exc_value])
            return True  # Don't propagate

        def catch_return_sock_exc(exc_type, exc_value, exc_traceback):
            history.extend(['return_sock_exc', exc_value])
            return True  # Don't propagate

        def get_socket():
            # Blocks until socket is available, since max_concurrent is 1
            pool.get_socket()
            loop.add_callback(raise_callback)

        my_assert = AssertionError('foo')

        def raise_callback():
            history.append('raise')
            raise my_assert

        def return_socket():
            with stack_context.ExceptionStackContext(catch_return_sock_exc):
                pool.maybe_return_socket(sock_info)

            main_gr.switch()

        with stack_context.ExceptionStackContext(catch_get_sock_exc):
            loop.add_callback(greenlet.greenlet(get_socket).switch)

        greenlet.greenlet(return_socket).switch()

        yield gen.Task(loop.add_timeout, datetime.timedelta(seconds=0.1))

        # 'return_sock_exc' was *not* added to history, because stack context
        # wasn't leaked from return_socket to get_socket.
        self.assertEqual(['raise', 'get_sock_exc', my_assert], history)
        cx.close()
Beispiel #22
0
 def __after_cpp_timer(self):
     """after CPP scheduled in get_signal"""
     self.tasklet = greenlet.greenlet(self.__restore_fan_damper)
     self.tasklet.switch()
     _log.debug("After CPP Event, returning to normal operations")
     self.tasklet = greenlet.greenlet(self.__restore_cooling_setpoint)
     self.tasklet.switch()
     timer = settings.after_time
     self.after_timer = self.periodic_timer(timer, self.__after_cpp_cooling)
Beispiel #23
0
 def wrapped(*args, **kwargs):
     fut = asyncio.Future()
     def green():
         try:
             fut.set_result(func(*args, **kwargs))
         except BaseException as e:
             fut.set_exception(e)
     greenlet.greenlet(green).switch()
     return fut
Beispiel #24
0
    def wrapper(*args, **kwargs):
        future = Future()

        def patched():
            with patch:
                result = fn(*args, **kwargs)
                future.set_result(result)

        greenlet.greenlet(patched).switch()
        return future
Beispiel #25
0
    def __init__(self):
        self.input_stream = MailBox()
        self.output_stream = MailBox()

        self._buffer = Buffer()

        self._wait_state = greenlet(self._do_wait)
        self._word_state = greenlet(self._do_word)
        self._number_state = greenlet(self._do_number)
        self._end_state = greenlet(self._do_end)
Beispiel #26
0
 def f():
     g1 = greenlet(fmain)
     g1.switch(seen)
     someref.append(g1)
     del g1
     gc.collect()
     lock.release()
     lock2.acquire()
     greenlet()   # trigger release
     lock.release()
     lock2.acquire()
Beispiel #27
0
    def wrapped(*args, target=None, **kwargs):
        def generator():
            # This is the generator that the wrapped function will consume from
            while True:
                item = greenlet.getcurrent().parent.switch(sentinel)
                if isinstance(item, GeneratorExit):
                    return
                else:
                    yield item

        def run_target():
            # greenlet executing wrapped function
            fn(generator(), *args, **kwargs)

        def run_target_generator():
            for item in fn(generator(), *args, **kwargs):
                greenlet.getcurrent().parent.switch(item)

        if inspect.isgeneratorfunction(fn):
            # Wrapping a filter (consumes an iterator, is a generator)
            g_consume = greenlet(run_target_generator)
            g_consume.switch()

            try:
                while True:
                    try:
                        item = (yield)
                    except Exception as e:
                        g_consume.throw(e)
                    else:
                        value = g_consume.switch(item)

                    # Feed any values the generator yields down the pipeline
                    while value is not sentinel:
                        if target is not None:
                            target.send(value)
                        value = g_consume.switch()
            except GeneratorExit as e:
                g_consume.switch(e)
        else:
            # Wrapping a sink (consumes an iterator)
            g_consume = greenlet(run_target)
            g_consume.switch()

            try:
                while True:
                    try:
                        item = (yield)
                    except Exception as e:
                        g_consume.throw(e)
                    else:
                        g_consume.switch(item)
            except GeneratorExit as e:
                g_consume.switch(e)
Beispiel #28
0
 def test_exception(self):
     seen = []
     g1 = greenlet(fmain)
     g2 = greenlet(fmain)
     g1.switch(seen)
     g2.switch(seen)
     g2.parent = g1
     self.assertEqual(seen, [])
     self.assertRaises(SomeError, g2.switch)
     self.assertEqual(seen, [SomeError])
     g2.switch()
     self.assertEqual(seen, [SomeError])
Beispiel #29
0
def test_exception():
    seen = []
    g1 = greenlet(fmain)
    g2 = greenlet(fmain)
    g1.switch(seen)
    g2.switch(seen)
    g2.parent = g1
    assert seen == []
    raises(SomeError, g2.switch)
    assert seen == [SomeError]
    g2.switch()
    assert seen == [SomeError]
Beispiel #30
0
def main(iterator, map_func, sink_func, pool_size):
    """Execute green_producer and green_consumer together"""
    queue = gevent.queue.Queue()
    producer_instance = greenlet(green_producer)
    consumer_instance = greenlet(green_consumer_sink)
    consumer_args = (sink_func, queue, producer_instance)

    # Initialize each greenlet and assume that it will immediately
    # return control back
    producer_instance.switch(
        iterator, map_func, queue, consumer_instance, pool_size,
        consumer_args)
    consumer_instance.switch()
Beispiel #31
0
from greenlet import greenlet


def test1():
    print('start test1')
    gr2.switch()
    print('end test1')


def test2():
    print('start test2')
    gr1.switch()
    print('end test2')


gr1 = greenlet(test1)
gr2 = greenlet(test2)

gr1.switch()
Beispiel #32
0
 def test_event_timeout(self):
     event = MotorGreenletEvent(self.io_loop, tornado_framework)
     waiter = greenlet.greenlet(partial(event.wait, timeout_seconds=0))
     waiter.switch()
     yield self.tick()
     self.assertFalse(waiter)  # Unblocked, finished.
Beispiel #33
0
    @version: 1.0
    @author: li
    @license: Apache Licence 
    @contact: [email protected]
    @site: 
    @software: PyCharm
    @file: coroutine_ex1.py
    @time: 2018/5/27 20:32
    @desc: 使用greenlet实现协程的手动切换
"""
from greenlet import greenlet


def run1():
    print(12)
    gr2.switch()
    print(34)
    gr2.switch()


def run2():
    print(56)
    gr1.switch()
    print(78)


if __name__ == '__main__':
    gr1 = greenlet(run1)
    gr2 = greenlet(run2)
    gr1.switch()
'''

from greenlet import greenlet
import time


def consumer(n):
    r = ''
    while True:
        n = gr_p.switch(r)
        if not n:
            return
        print('[Consumer] consuming %s ...' % n)
        r = '200 OK'


def producer(r):
    r = gr_c.switch(None)
    n = 0
    while n < 5:
        n += 1
        print('[Producer] porduced %s ...' % n)
        r = gr_c.switch(n)
        print('[Producer] Consumer return %s ...' % r)


gr_c = greenlet(consumer)
gr_p = greenlet(producer)

gr_p.switch(None)
 def test_switch(self):
     self.assertEqual(
         50, _test_extension.test_switch(greenlet.greenlet(lambda: 50)))
import time

from greenlet import greenlet


def t1():
    while True:
        print("----a---")
        gr2.switch()
        time.sleep(0.5)


def t2():
    while True:
        print("----b---")
        gr1.switch()
        time.sleep(0.5)


gr1 = greenlet(t1)
gr2 = greenlet(t2)

gr1.switch()

def task1():
    while True:
        print("-" * 20)
        print("---task1---")
        grl2.switch()
        time.sleep(0.1)


def task2():
    while True:
        print("---task2---")
        grl1.switch()
        time.sleep(0.1)


grl1 = greenlet(task1)
grl2 = greenlet(task2)


def main():
    """使用greenlet完成多任务"""
    # 需要首先 sudo pip3 install greenlet

    grl1.switch()


if __name__ == '__main__':
    main()
Beispiel #38
0
 def __init__(self, post_call, chunk_size=None):
     super(GreenletRequestsIO, self).__init__(post_call, chunk_size)
     self._cur_greenlet = greenlet.getcurrent()
     self._writer_greenlet = greenlet(self._async_func)
     self._last_data = None
     self._writer_greenlet.switch()
Beispiel #39
0
def twisted_greenlet(request):
    global gr_twisted
    gr_twisted = greenlet.greenlet(reactor.run)
    failure.Failure.cleanFailure = lambda self: None  # give me better tracebacks
    request.addfinalizer(stop_twisted_greenlet)
    return gr_twisted
Beispiel #40
0
# 实现协程方法
from greenlet import greenlet


def func1():
    print(1)
    gr2.switch()
    print(2)
    gr2.switch()


def func2():
    print(3)
    gr1.switch()
    print(4)
    gr1.switch()


gr1 = greenlet(func1)
gr2 = greenlet(func2)
# 不停进行切换 通过switch切换执行
gr1.switch()
Beispiel #41
0
from greenlet import greenlet


def test1():
    print(12)
    gr2.switch()            #将转至另一个协程
    print(34)
    gr2.switch()

def test2():
    print(56)
    gr1.switch()
    print(78)

 



gr1 = greenlet(test1)       #启动一个协程
gr2 = greenlet(test2)

gr1.switch()        #手工的切换
Beispiel #42
0
from greenlet import greenlet


def a():  # 任务A
    for i in range(5):
        print('A' + str(i))
        gb.switch()  # 切换
        time.sleep(0.1)


def b():  # 任务B
    for i in range(5):
        print('B' + str(i))
        gc.switch()
        time.sleep(0.1)


def c():  # 任务C
    for i in range(5):
        print('C' + str(i))
        ga.switch()
        time.sleep(0.1)


if __name__ == '__main__':
    ga = greenlet(a)
    gb = greenlet(b)
    gc = greenlet(c)

    ga.switch()
Beispiel #43
0
def test1():
    print gt.getcurrent()   # 协程1
    print 1
    g2.switch()
    print 11


def test2():
    print 2
    g1.switch()
    print 22


print gt.getcurrent()       # 主协程
g1 = greenlet(test1)
g2 = greenlet(test2)
g1.switch()                 # 1 2 11
print gt.getcurrent()       # 主协程
print g1.dead               # True
print g2.dead               # False
g2.switch()                 # 22


u"""
    1.只有在test1函数是,是协程1
    2.22没有输出,原因是test2切换到test1后没有切换回来,等g2的引用计数清零是会
      抛出GreenletExit异常
    3.执行完对应的函数协程才会退出
    
    4.需要手动切换,不够智能
Beispiel #44
0
#!/usr/bin/env python3
#coding:utf-8

from greenlet import greenlet


def func1():
    print(12)
    t2.switch()
    print(56)
    t2.switch()


def func2():
    print(98)
    t1.switch()
    print(55)
    t2.switch()


t1 = greenlet(func1)
t2 = greenlet(func2)  #定义了两个切换器
t1.switch()
 def test_inactive_weakref(self):
     o = weakref.ref(greenlet.greenlet())
     gc.collect()
     self.assertEqual(o(), None)
Beispiel #46
0
 async def aexec(code):
     green = greenlet.greenlet(gexec)
     gen = green.switch(code)
     for future in gen:
         await future
 def _dead_greenlet():
     g = greenlet.greenlet(lambda: None)
     g.switch()
     return g
Beispiel #48
0
 def gexec(code):
     child = greenlet.greenlet(exec)
     gawait = GreenAwait(child)
     child.switch(code, {'gawait': gawait, 'bot': bot, 'msg': msg})
     yield from gawait
Beispiel #49
0
# # -*- coding: utf-8 -*-
from greenlet import greenlet, getcurrent
import time
def test1():
    print 12
    gr2.parent.switch()
    print 34

def test2():
    print 56
    gr1.switch()
    print 78
gr1 = greenlet(test1)
gr2 = greenlet(test2)

def get_ack():
    while True:
        time.sleep(2)
        gl_self = getcurrent()
        gl_self.parent.switch()

gl_ack = greenlet(get_ack)
for i in range(7):
    print('send message %s' %i)
    gl_ack.switch()
Beispiel #50
0
from greenlet import greenlet
import time


# 协程利用程序的IO阻塞 来切换任务
def demo1():
    while True:
        print("demo1")
        gr2.switch()
        time.sleep(0.5)


def demo2():
    while True:
        print("demo2")
        gr1.switch()
        time.sleep(0.5)


gr1 = greenlet(demo1)
# print(greenlet.__doc__)
gr2 = greenlet(demo2)

gr1.switch()
Beispiel #51
0
        time.sleep(0.5)


def main():
    w1 = work1()  # 生成器对象
    w2 = work2()  # 生成器对象2
    while True:
        next(w1)
        next(w2)


def f(n):
    for i in range(n):
        print(gevent.getcurrent(), i)  # 打印当前协程实例对象
        gevent.sleep(0.5)


if __name__ == '__main__':
    # main()  demo1  手写
    gr1 = greenlet(gre1func)  # 创建 greenlet 对象  demo2
    gr2 = greenlet(gre2func)  # 创建 greenlet 对象  demo2
    # gr2.switch()

    g1 = gevent.spawn(f, 5)  # 给f传参
    g2 = gevent.spawn(f, 6)  # 给f传参
    g3 = gevent.spawn(f, 7)  # 给f传参
    # g1.join()  # 默认情况下使用gevent不自动切换
    # g2.join()  # 默认情况下使用gevent不自动切换
    # g3.join()  # 默认情况下使用gevent不自动切换
    gevent.joinall([g1, g2, g3])
Beispiel #52
0
#! /usr/bin/env python3
# encoding: utf-8
"""
    greenlet_1.py
Created by PythonStudy on 2017/5/31 上午10:07
Copyright 2017 azhen All rights reserved.
"""

from greenlet import greenlet

from greenlet import greenlet


def test1():
    print(12)
    gr2.switch()
    print(34)
    gr2.switch()


def test2():
    print(56)
    gr1.switch()
    print(78)


gr1 = greenlet(test1)  # 生成 并执行
gr2 = greenlet(test2)  # 生成 并执行
gr1.switch()
    def test_switch_kwargs(self):
        def foo(x, y):
            return x * y

        g = greenlet.greenlet(foo)
        self.assertEqual(6, _test_extension.test_switch_kwargs(g, x=3, y=2))
Beispiel #54
0
#coding:utf-8
from greenlet import greenlet
import time


def worker1():
    num = 0
    while num < 10:
        print("this is worker 1")
        num += 1
        gr2.switch()
        time.sleep(0.5)


def worker2():
    num = 0
    while num < 10:
        print("this is worker 2")
        num += 1
        gr1.switch()
        time.sleep(0.5)


gr1 = greenlet(worker1)
gr2 = greenlet(worker2)

#切换到gr1中运行
gr1.switch()
import time
from greenlet import greenlet


def worker1():
    # for i in range(n):
    while True:
        print("in worker1")
        # 切换到第二个协程执行
        g2.switch()
        time.sleep(1)


def worker2():
    # for i in range(n):
    while True:
        print("in worker2")
        # 切换到第一个协程执行
        g1.switch()
        time.sleep(1)


# 创建协程对象
g1 = greenlet(worker1)
g2 = greenlet(worker2)
# 切换到协程执行
g1.switch()
Beispiel #56
0
def test1():
    print(12)
    try:
        gr2.switch()
    except NameError:
        print(90)
    print(34)


def test2():
    print(56)
    raise NameError


gr1 = greenlet(test1)
gr2 = greenlet(test2, gr1)
gr1.switch()

from greenlet import greenlet


def consumer():
    last = ''
    while True:
        receival = pro.swith(last)
        if receival is not None:
            print('Cousumer %s' % (receival))
            last = receival


def fun1():
    print(1)
    gr2.switch()
    print(2)
    gr2.switch()


def fun2():
    print(3)
    gr1.switch()
    print(4)


gr1 = greenlet(fun1)
gr2 = greenlet(fun2)

gr1.switch()
print("-----------------------yield-----------------------------")


def fun3():
    yield 1
    yield from fun4()
    yield 2


def fun4():
    yield 3
    yield 4
Beispiel #58
0
#     for i in range(40):
#         pool.apply_async(func=foo, args=(i,))
#
#     pool.close()
#     pool.join()

from greenlet import greenlet


def func1():
    print("111111111")
    grl2.switch()
    print("222222222")
    grl2.switch()


def func2():
    print("3333")
    grl1.switch()
    print(4444444)


def func3():
    print("切换到func3")


if __name__ == '__main__':
    grl1 = greenlet(func1)
    grl2 = greenlet(func2)

    grl1.switch()
Beispiel #59
0
 def handle_stream(self, stream, address):
     itrans = self.input_transport_factory.getTransport(stream)
     otrans = self.output_transport_factory.getTransport(stream) if self.output_transport_factory else None
     child_gr = greenlet.greenlet(self.process)
     child_gr.switch(itrans, otrans)
hqs paly 2
"""

# 检查greenlet面对i/o的情况是否可以切换:不能切换,无法提升效率
from greenlet import greenlet
import time


def eat(name):
    print("%s eat 1" % name)
    time.sleep(10)
    g2.switch("hqs")
    print("%s eat 2" % name)
    g2.switch()


def play(name):
    print("%s play 1" % name)
    g1.switch()
    print("%s paly 2" % name)


g1 = greenlet(eat)
g2 = greenlet(play)
g1.switch('egon')
"""
egon eat 1   # 这一步卡了足足10秒
hqs play 1
egon eat 2
hqs paly 2
"""