我们从Python开源项目中,提取了以下6个代码示例,用于说明如何使用asyncio.BoundedSemaphore()。
def __init__(self, client=None, download_strategy=None, request_strategy=None): if not client: # Get the event loop and initialize a client session if not provided self.loop = asyncio.get_event_loop() self.client = aiohttp.ClientSession(loop=self.loop) else: # Or grab the event loop from the client session self.loop = client._loop self.client = client # Configuration objects managing download and request strategies self._download_strategy = download_strategy or DownloadStrategy() # chunk_size, home, skip_cached self._request_strategy = request_strategy or Lenient() # concurrent, max_attempts, timeout # Bounded semaphore guards how many requests can run concurrently self._main_semaphore = asyncio.BoundedSemaphore(self._request_strategy.concurrent)
def __init__(self, loop, prefix: str = "aiotasks", concurrency: int = 5): self._loop_delay = loop self.task_prefix = prefix self.task_running_tasks = dict() self.task_available_tasks = dict() self.task_concurrency = concurrency self.task_list_name = "{}:{}".format(self.task_prefix, "tasks") # Semaphore for task_concurrency self.task_concurrency_sem = \ asyncio.BoundedSemaphore(self.task_concurrency, loop=self._loop_delay)
def test_release_not_acquired(self): sem = asyncio.BoundedSemaphore(loop=self.loop) self.assertRaises(ValueError, sem.release)
def _scan(targets: Set[str], ports: Set[int], config: DockerScanModel, loop: asyncio.AbstractEventLoop): max_concurrency = asyncio.BoundedSemaphore(int(config.concurrency), loop=loop) results = [] tasks = [] for target in targets: for port in ports: await max_concurrency.acquire() tasks.append(loop.create_task(_check_ports( target, port, loop, max_concurrency, results, config ))) await asyncio.wait(tasks, loop=loop) return results