Python asyncio 模块,Condition() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用asyncio.Condition()

项目:mockaioredis    作者:kblin    | 项目源码 | 文件源码
def __init__(self, address, db=0, password=0, encoding=None,
                 *, minsize, maxsize, commands_factory, ssl=None, loop=None):
        if loop is None:
            loop = asyncio.get_event_loop()

        self._address = address
        self._db = db
        self._password = password
        self._encoding = encoding
        self._minsize = minsize
        self._maxsize = maxsize
        self._factory = commands_factory
        self._ssl = ssl
        self._loop = loop

        # fake it here, we always only have one connection
        self._pool = collections.deque(maxlen=1)
        self._used = set()
        self._acquiring = 0

        self._cond = asyncio.Condition(loop=loop)
        self._close_state = asyncio.Event(loop=loop)
        self._close_waiter = asyncio.ensure_future(self._do_close(), loop=loop)
项目:aiossdb    作者:Microndgt    | 项目源码 | 文件源码
def __init__(self, address, *, password=None, parser=None, encoding=None, minsize, maxsize,
                 connection_cls=None, timeout=None, loop=None):
        assert isinstance(minsize, int) and minsize >= 0, ("minsize must be int >=0", minsize, type(minsize))
        assert isinstance(maxsize, int) and maxsize >= minsize, (
            "maxsize must be int >= minsize", maxsize, type(maxsize), minsize)
        if loop is None:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
        self._address = address
        self._password = password
        self._parser_class = parser
        self._timeout = timeout
        self._loop = loop
        self._used = set()
        self._connection_cls = connection_cls
        self._pool = collections.deque(maxlen=maxsize)
        self._minsize = minsize
        self._maxsize = maxsize
        self._encoding = encoding
        # ??release?????????????????????????????
        self._cond = asyncio.Condition(lock=asyncio.Lock(loop=loop), loop=loop)
        self._waiter = None
        self._closing = False
        self._closed = False
项目:paraproxio    作者:intagger    | 项目源码 | 文件源码
def __init__(self,
                 cache_dir: str,
                 parallels,
                 part_size,
                 chunk_size,
                 loop,
                 server_logger=server_logger):
        self._cache_dir = cache_dir
        self._parallels = parallels
        self._part_size = part_size
        self._chunk_size = chunk_size
        self._loop = loop if loop is not None else asyncio.get_event_loop()
        self._server_logger = server_logger
        self._state_condition = asyncio.Condition(loop=self._loop)

        ensure_future(self._init_cache(), loop=self._loop)
项目:FCR    作者:facebookincubator    | 项目源码 | 文件源码
def __init__(self, service, name=None, executor=None):
        super().__init__(service, name)
        self._state = State.CREATE

        # A Task may want to run blocking calls in separate thread. To run a
        # method in separate thread, task can use the _run_in_executor() method.
        # User can create their own executor instead using the default one
        # created by the asyncio. This allows user control over the type of
        # executor (task/threads) and its properties (e.g. num_workers)
        self._executor = executor

        # _update_event can be used to notify coroutines about the change in
        # state in this service. e.g. run() has completed
        self._update_event = asyncio.Condition(loop=self.loop)

        self.set_state(State.INIT)

        coro = self.start()
        # fixup task name to show actual task in logs
        coro.__qualname__ = self._objname
        self._task = asyncio.ensure_future(coro, loop=self.loop)

        self._ALL_TASKS[self._objname] = self
项目:aiothrift    作者:ryanwang520    | 项目源码 | 文件源码
def __init__(self, service, address,
                 *, minsize, maxsize, loop=None, timeout=None):
        assert isinstance(minsize, int) and minsize >= 0, (
            "minsize must be int >= 0", minsize, type(minsize))
        assert maxsize is not None, "Arbitrary pool size is disallowed."
        assert isinstance(maxsize, int) and maxsize > 0, (
            "maxsize must be int > 0", maxsize, type(maxsize))
        assert minsize <= maxsize, (
            "Invalid pool min/max sizes", minsize, maxsize)
        if loop is None:
            loop = asyncio.get_event_loop()
        self._address = address
        self.minsize = minsize
        self.maxsize = maxsize
        self._loop = loop
        self._pool = collections.deque(maxlen=maxsize)
        self._used = set()
        self._acquiring = 0
        self._cond = asyncio.Condition(loop=loop)
        self._service = service
        self._timeout = timeout
        self.closed = False
        self._release_tasks = set()
项目:aioimaplib    作者:bamthomas    | 项目源码 | 文件源码
def __init__(self, server_state, fetch_chunk_size=0, capabilities=CAPABILITIES,
                 loop=asyncio.get_event_loop()):
        self.uidvalidity = int(datetime.now().timestamp())
        self.capabilities = capabilities
        self.state_to_send = list()
        self.delay_seconds = 0
        self.loop = loop
        self.fetch_chunk_size = fetch_chunk_size
        self.transport = None
        self.server_state = server_state
        self.user_login = None
        self.user_mailbox = None
        self.idle_tag = None
        self.idle_task = None
        self.state = NONAUTH
        self.state_condition = asyncio.Condition()
        self.append_literal_command = None
项目:aioimaplib    作者:bamthomas    | 项目源码 | 文件源码
def __init__(self, loop, conn_lost_cb=None):
        self.loop = loop
        self.transport = None
        self.state = STARTED
        self.state_condition = asyncio.Condition()
        self.capabilities = set()
        self.pending_async_commands = dict()
        self.pending_sync_command = None
        self.idle_queue = asyncio.Queue()
        self.imap_version = None
        self.literal_data = None
        self.incomplete_line = b''
        self.current_command = None
        self.conn_lost_cb = conn_lost_cb

        self.tagnum = 0
        self.tagpre = int2ap(random.randint(4096, 65535))
项目:jussi    作者:steemit    | 项目源码 | 文件源码
def __init__(self, url, minsize, maxsize, loop,
                 timeout, *, pool_recycle, **kwargs):
        if minsize < 0:
            raise ValueError("minsize should be zero or greater")
        if maxsize < minsize and maxsize != 0:
            raise ValueError("maxsize should be not less than minsize")
        self._url = url
        self._minsize = minsize
        self._loop = loop
        self._timeout = timeout
        self._recycle = pool_recycle

        self._on_connect = None  # on_connect
        self._conn_kwargs = kwargs
        self._acquiring = 0
        self._free = collections.deque(maxlen=maxsize or None)
        self._cond = asyncio.Condition(loop=loop)
        self._used = set()
        self._terminated = set()
        self._connect_message_counter = collections.Counter()
        self._closing = False
        self._closed = False
项目:CEX.IO-Client-Python3.5    作者:cexioltd    | 项目源码 | 文件源码
def __init__(self, _config):
        super().__init__(_config)

        def validator(m):
            try:
                ok = m['ok']
                if ok == 'ok':
                    return m['data']
                elif ok == 'error':
                    raise ErrorMessage(m['data']['error'])
                else:
                    error = InvalidMessage(m)
            except KeyError:
                error = InvalidMessage(m)
            raise error

        resolver = RequestResponseFutureResolver(name='', op_name_get_path='e',
                                                 key_set_path='oid', key_get_path='oid')
        self.message_map = (
            ({  'e': None,
                'data': None,
                'oid': None,
                'ok': None, }, resolver + validator),

            ({  'e': None, }, self.on_notification),
        )
        router = MessageRouter(self.message_map, sink=self.on_unhandled)
        self.set_router(router)
        self.set_resolver(resolver)
        self.__n_future = None
        self.__n_cond = asyncio.Condition()
项目:pymotw3    作者:reingart    | 项目源码 | 文件源码
def main(loop):
    # Create a condition
    condition = asyncio.Condition()

    # Set up tasks watching the condition
    consumers = [
        consumer(condition, i)
        for i in range(5)
    ]

    # Schedule a task to manipulate the condition variable
    loop.create_task(manipulate_condition(condition))

    # Wait for the consumers to be done
    await asyncio.wait(consumers)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_ctor_loop(self):
        loop = mock.Mock()
        cond = asyncio.Condition(loop=loop)
        self.assertIs(cond._loop, loop)

        cond = asyncio.Condition(loop=self.loop)
        self.assertIs(cond._loop, self.loop)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_ctor_noloop(self):
        asyncio.set_event_loop(self.loop)
        cond = asyncio.Condition()
        self.assertIs(cond._loop, self.loop)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_wait_cancel(self):
        cond = asyncio.Condition(loop=self.loop)
        self.loop.run_until_complete(cond.acquire())

        wait = asyncio.Task(cond.wait(), loop=self.loop)
        self.loop.call_soon(wait.cancel)
        self.assertRaises(
            asyncio.CancelledError,
            self.loop.run_until_complete, wait)
        self.assertFalse(cond._waiters)
        self.assertTrue(cond.locked())
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_wait_unacquired(self):
        cond = asyncio.Condition(loop=self.loop)
        self.assertRaises(
            RuntimeError,
            self.loop.run_until_complete, cond.wait())
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_wait_for(self):
        cond = asyncio.Condition(loop=self.loop)
        presult = False

        def predicate():
            return presult

        result = []

        @asyncio.coroutine
        def c1(result):
            yield from cond.acquire()
            if (yield from cond.wait_for(predicate)):
                result.append(1)
                cond.release()
            return True

        t = asyncio.Task(c1(result), loop=self.loop)

        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)

        self.loop.run_until_complete(cond.acquire())
        cond.notify()
        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)

        presult = True
        self.loop.run_until_complete(cond.acquire())
        cond.notify()
        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([1], result)

        self.assertTrue(t.done())
        self.assertTrue(t.result())
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_notify_all(self):
        cond = asyncio.Condition(loop=self.loop)

        result = []

        @asyncio.coroutine
        def c1(result):
            yield from cond.acquire()
            if (yield from cond.wait()):
                result.append(1)
                cond.release()
            return True

        @asyncio.coroutine
        def c2(result):
            yield from cond.acquire()
            if (yield from cond.wait()):
                result.append(2)
                cond.release()
            return True

        t1 = asyncio.Task(c1(result), loop=self.loop)
        t2 = asyncio.Task(c2(result), loop=self.loop)

        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)

        self.loop.run_until_complete(cond.acquire())
        cond.notify_all()
        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([1, 2], result)

        self.assertTrue(t1.done())
        self.assertTrue(t1.result())
        self.assertTrue(t2.done())
        self.assertTrue(t2.result())
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_notify_unacquired(self):
        cond = asyncio.Condition(loop=self.loop)
        self.assertRaises(RuntimeError, cond.notify)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_notify_all_unacquired(self):
        cond = asyncio.Condition(loop=self.loop)
        self.assertRaises(RuntimeError, cond.notify_all)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_repr(self):
        cond = asyncio.Condition(loop=self.loop)
        self.assertTrue('unlocked' in repr(cond))
        self.assertTrue(RGX_REPR.match(repr(cond)))

        self.loop.run_until_complete(cond.acquire())
        self.assertTrue('locked' in repr(cond))

        cond._waiters.append(mock.Mock())
        self.assertTrue('waiters:1' in repr(cond))
        self.assertTrue(RGX_REPR.match(repr(cond)))

        cond._waiters.append(mock.Mock())
        self.assertTrue('waiters:2' in repr(cond))
        self.assertTrue(RGX_REPR.match(repr(cond)))
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_context_manager_no_yield(self):
        cond = asyncio.Condition(loop=self.loop)

        try:
            with cond:
                self.fail('RuntimeError is not raised in with expression')
        except RuntimeError as err:
            self.assertEqual(
                str(err),
                '"yield from" should be used as context manager expression')

        self.assertFalse(cond.locked())
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_explicit_lock(self):
        lock = asyncio.Lock(loop=self.loop)
        cond = asyncio.Condition(lock, loop=self.loop)

        self.assertIs(cond._lock, lock)
        self.assertIs(cond._loop, lock._loop)
项目:annotated-py-asyncio    作者:hhstore    | 项目源码 | 文件源码
def test_ambiguous_loops(self):
        loop = self.new_test_loop()
        self.addCleanup(loop.close)

        lock = asyncio.Lock(loop=self.loop)
        with self.assertRaises(ValueError):
            asyncio.Condition(lock, loop=loop)
项目:Learning-Concurrency-in-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def main(loop):
    # Create a condition
    condition = asyncio.Condition()

    # Set up tasks watching the condition
    consumers = [
        consumer(condition, i)
        for i in range(5)
    ]

    # Schedule a task to manipulate the condition variable
    loop.create_task(manipulate_condition(condition))

    # Wait for the consumers to be done
    await asyncio.wait(consumers)
项目:device-updater    作者:spark    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super().__init__(threading.Condition(), *args, **kwargs)
项目:device-updater    作者:spark    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super().__init__(asyncio.Condition(), *args, **kwargs)
项目:paraproxio    作者:intagger    | 项目源码 | 文件源码
def __init__(
            self,
            url: str,
            file_length: int,
            *,
            parallels: int = DEFAULT_PARALLELS,
            part_size: int = DEFAULT_PART_SIZE,
            chunk_size: int = DEFAULT_CHUNK_SIZE,
            loop: AbstractEventLoop = None,
            server_logger=server_logger,
            buffer_dir: str = DEFAULT_BUFFER_DIR):
        assert parallels > 1

        self._url = url
        self._file_length = file_length
        self._part_size = part_size
        self._parallels = parallels
        self._chunk_size = chunk_size
        self._loop = loop if loop is not None else asyncio.get_event_loop()
        self._server_logger = server_logger
        self._download_dir = os.path.join(buffer_dir, get_unique_name())

        self._create_download_dir()

        # Calculate bytes ranges.
        self._bytes_ranges = get_bytes_ranges_by_part_size(self._file_length, self._part_size)
        self._parts = len(self._bytes_ranges)

        if self._parts < self._parallels:
            self._bytes_ranges = get_bytes_ranges_by_parts(self._file_length, self._parallels)
            self._parts = len(self._bytes_ranges)

        self._state_condition = asyncio.Condition(loop=self._loop)
项目:FCR    作者:facebookincubator    | 项目源码 | 文件源码
def __init__(self, service, devinfo, options, loop):

        # Setup devinfo as this is needed to create the logger
        self._devinfo = devinfo

        super().__init__(service)

        self._opts = options
        self._hostname = devinfo.hostname

        self._extra_info = {}
        self._exit_status = None

        # use the specified username/password or fallback to device defaults
        self._username = options.get("username") or devinfo.username
        self._password = options.get("password") or devinfo.password
        self._client_ip = options["client_ip"]
        self._client_port = options["client_port"]
        self._loop = loop

        self._connected = False
        self._event = asyncio.Condition(loop=self._loop)

        self.logger.info("Created key=%s", self.key)

        # Record the session in the cache
        self._ALL_SESSIONS[self.key] = self
项目:aiotk    作者:AndreLouisCaron    | 项目源码 | 文件源码
def __init__(self, loop=None):
        self._loop = loop or asyncio.get_event_loop()
        self._lock = asyncio.Lock(loop=self._loop)
        self._cond = asyncio.Condition(self._lock, loop=self._loop)
        self._pool = set()
        self._task = None
        self._done = False
        self._idle = asyncio.Condition(self._lock, loop=self._loop)
        self._busy = asyncio.Condition(self._lock, loop=self._loop)
项目:ddmbot    作者:Budovi    | 项目源码 | 文件源码
def __init__(self, *, loop=None):
        self._loop = loop if loop is not None else asyncio.get_event_loop()
        self._main_lock = threading.Lock()

        self._coroutine_lock = asyncio.Lock(loop=self._loop)
        self._condition = asyncio.Condition(lock=self._coroutine_lock, loop=self._loop)
项目:vlt-Music    作者:Mondanzo    | 项目源码 | 文件源码
def __init__(self):
        super().__init__()

        # Load Config
        self.configPath = "config.yml"
        with open(self.configPath, "r") as config:
            self.cfg = yaml.load(config)

        # Inti default variables.
        self.requests = True
        self.auto_shutdown = False
        self.voiceClient = None
        self.info_channel = None
        self.stream_player = None
        self.is_playing = False
        self.playlist = list()
        self.skip_list = list()
        self.role = None
        self.log = Logger("logs/")
        self.conditions = asyncio.Condition()
        self.queue = music.Playlist()
        self.__version__ = '2.8.2'

        # Get the settings from the config.
        self.skips = self.cfg['ReqSkips']
        self.p = self.cfg['Prefix']
        self.volume = self.cfg['Volume']
        self.allowedLinks = self._load_allowed_sites()
        self._load_opus()
        self.__start_bot(self.cfg['Token'], bot=True)

    # On message event (Commands)
    # #MoreCommandsIncomming
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_ctor_loop(self):
        loop = mock.Mock()
        cond = asyncio.Condition(loop=loop)
        self.assertIs(cond._loop, loop)

        cond = asyncio.Condition(loop=self.loop)
        self.assertIs(cond._loop, self.loop)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_ctor_noloop(self):
        asyncio.set_event_loop(self.loop)
        cond = asyncio.Condition()
        self.assertIs(cond._loop, self.loop)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_wait_cancel(self):
        cond = asyncio.Condition(loop=self.loop)
        self.loop.run_until_complete(cond.acquire())

        wait = asyncio.Task(cond.wait(), loop=self.loop)
        self.loop.call_soon(wait.cancel)
        self.assertRaises(
            asyncio.CancelledError,
            self.loop.run_until_complete, wait)
        self.assertFalse(cond._waiters)
        self.assertTrue(cond.locked())
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_wait_unacquired(self):
        cond = asyncio.Condition(loop=self.loop)
        self.assertRaises(
            RuntimeError,
            self.loop.run_until_complete, cond.wait())
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_wait_for(self):
        cond = asyncio.Condition(loop=self.loop)
        presult = False

        def predicate():
            return presult

        result = []

        @asyncio.coroutine
        def c1(result):
            yield from cond.acquire()
            if (yield from cond.wait_for(predicate)):
                result.append(1)
                cond.release()
            return True

        t = asyncio.Task(c1(result), loop=self.loop)

        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)

        self.loop.run_until_complete(cond.acquire())
        cond.notify()
        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)

        presult = True
        self.loop.run_until_complete(cond.acquire())
        cond.notify()
        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([1], result)

        self.assertTrue(t.done())
        self.assertTrue(t.result())
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_notify_all(self):
        cond = asyncio.Condition(loop=self.loop)

        result = []

        @asyncio.coroutine
        def c1(result):
            yield from cond.acquire()
            if (yield from cond.wait()):
                result.append(1)
                cond.release()
            return True

        @asyncio.coroutine
        def c2(result):
            yield from cond.acquire()
            if (yield from cond.wait()):
                result.append(2)
                cond.release()
            return True

        t1 = asyncio.Task(c1(result), loop=self.loop)
        t2 = asyncio.Task(c2(result), loop=self.loop)

        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)

        self.loop.run_until_complete(cond.acquire())
        cond.notify_all()
        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([1, 2], result)

        self.assertTrue(t1.done())
        self.assertTrue(t1.result())
        self.assertTrue(t2.done())
        self.assertTrue(t2.result())
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_notify_unacquired(self):
        cond = asyncio.Condition(loop=self.loop)
        self.assertRaises(RuntimeError, cond.notify)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_notify_all_unacquired(self):
        cond = asyncio.Condition(loop=self.loop)
        self.assertRaises(RuntimeError, cond.notify_all)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_repr(self):
        cond = asyncio.Condition(loop=self.loop)
        self.assertTrue('unlocked' in repr(cond))
        self.assertTrue(RGX_REPR.match(repr(cond)))

        self.loop.run_until_complete(cond.acquire())
        self.assertTrue('locked' in repr(cond))

        cond._waiters.append(mock.Mock())
        self.assertTrue('waiters:1' in repr(cond))
        self.assertTrue(RGX_REPR.match(repr(cond)))

        cond._waiters.append(mock.Mock())
        self.assertTrue('waiters:2' in repr(cond))
        self.assertTrue(RGX_REPR.match(repr(cond)))
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_context_manager_no_yield(self):
        cond = asyncio.Condition(loop=self.loop)

        try:
            with cond:
                self.fail('RuntimeError is not raised in with expression')
        except RuntimeError as err:
            self.assertEqual(
                str(err),
                '"yield from" should be used as context manager expression')

        self.assertFalse(cond.locked())
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_explicit_lock(self):
        lock = asyncio.Lock(loop=self.loop)
        cond = asyncio.Condition(lock, loop=self.loop)

        self.assertIs(cond._lock, lock)
        self.assertIs(cond._loop, lock._loop)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_ambiguous_loops(self):
        loop = self.new_test_loop()
        self.addCleanup(loop.close)

        lock = asyncio.Lock(loop=self.loop)
        with self.assertRaises(ValueError):
            asyncio.Condition(lock, loop=loop)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_ctor_loop(self):
        loop = mock.Mock()
        cond = asyncio.Condition(loop=loop)
        self.assertIs(cond._loop, loop)

        cond = asyncio.Condition(loop=self.loop)
        self.assertIs(cond._loop, self.loop)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_ctor_noloop(self):
        asyncio.set_event_loop(self.loop)
        cond = asyncio.Condition()
        self.assertIs(cond._loop, self.loop)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_wait_cancel(self):
        cond = asyncio.Condition(loop=self.loop)
        self.loop.run_until_complete(cond.acquire())

        wait = asyncio.Task(cond.wait(), loop=self.loop)
        self.loop.call_soon(wait.cancel)
        self.assertRaises(
            asyncio.CancelledError,
            self.loop.run_until_complete, wait)
        self.assertFalse(cond._waiters)
        self.assertTrue(cond.locked())
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_wait_unacquired(self):
        cond = asyncio.Condition(loop=self.loop)
        self.assertRaises(
            RuntimeError,
            self.loop.run_until_complete, cond.wait())
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_wait_for(self):
        cond = asyncio.Condition(loop=self.loop)
        presult = False

        def predicate():
            return presult

        result = []

        @asyncio.coroutine
        def c1(result):
            yield from cond.acquire()
            if (yield from cond.wait_for(predicate)):
                result.append(1)
                cond.release()
            return True

        t = asyncio.Task(c1(result), loop=self.loop)

        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)

        self.loop.run_until_complete(cond.acquire())
        cond.notify()
        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)

        presult = True
        self.loop.run_until_complete(cond.acquire())
        cond.notify()
        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([1], result)

        self.assertTrue(t.done())
        self.assertTrue(t.result())
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_notify_all(self):
        cond = asyncio.Condition(loop=self.loop)

        result = []

        @asyncio.coroutine
        def c1(result):
            yield from cond.acquire()
            if (yield from cond.wait()):
                result.append(1)
                cond.release()
            return True

        @asyncio.coroutine
        def c2(result):
            yield from cond.acquire()
            if (yield from cond.wait()):
                result.append(2)
                cond.release()
            return True

        t1 = asyncio.Task(c1(result), loop=self.loop)
        t2 = asyncio.Task(c2(result), loop=self.loop)

        test_utils.run_briefly(self.loop)
        self.assertEqual([], result)

        self.loop.run_until_complete(cond.acquire())
        cond.notify_all()
        cond.release()
        test_utils.run_briefly(self.loop)
        self.assertEqual([1, 2], result)

        self.assertTrue(t1.done())
        self.assertTrue(t1.result())
        self.assertTrue(t2.done())
        self.assertTrue(t2.result())
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_notify_unacquired(self):
        cond = asyncio.Condition(loop=self.loop)
        self.assertRaises(RuntimeError, cond.notify)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_notify_all_unacquired(self):
        cond = asyncio.Condition(loop=self.loop)
        self.assertRaises(RuntimeError, cond.notify_all)