當前位置: 首頁>>代碼示例>>Python>>正文


Python trio.Lock方法代碼示例

本文整理匯總了Python中trio.Lock方法的典型用法代碼示例。如果您正苦於以下問題:Python trio.Lock方法的具體用法?Python trio.Lock怎麽用?Python trio.Lock使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在trio的用法示例。


在下文中一共展示了trio.Lock方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def __init__(
        self,
        local_name: str,
        conn: ConnectionAPI,
        subscriptions_changed: ConditionAPI,
        new_msg_func: Callable[[Broadcast], Awaitable[Any]],
    ) -> None:
        super().__init__(local_name, conn, new_msg_func)

        self._notify_lock = trio.Lock()  # type: ignore

        self._received_response = trio.Condition()  # type: ignore
        self._received_subscription = trio.Condition()  # type: ignore

        self._running = trio.Event()  # type: ignore
        self._stopped = trio.Event()  # type: ignore

        self._received_subscription = subscriptions_changed

        self._subscriptions_initialized = trio.Event()  # type: ignore

        self._running = trio.Event()  # type: ignore
        self._stopped = trio.Event()  # type: ignore
        self._ready = trio.Event()  # type: ignore 
開發者ID:ethereum,項目名稱:lahja,代碼行數:26,代碼來源:endpoint.py

示例2: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def __init__(self, app: ASGIFramework, config: Config, stream: trio.abc.Stream) -> None:
        self.app = app
        self.config = config
        self.protocol: ProtocolWrapper
        self.send_lock = trio.Lock()
        self.timeout_lock = trio.Lock()
        self.stream = stream

        self._keep_alive_timeout_handle: Optional[trio.CancelScope] = None 
開發者ID:pgjones,項目名稱:hypercorn,代碼行數:11,代碼來源:tcp_server.py

示例3: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def __init__(self, parent, nursery=None):
        self._stream = None
        self._stream_lock = trio.Lock()
        self._sockname = None
        self._parent = parent
        self._closing = False
        self._closed = False
        self._user_queries = {}
        self._cursor_cache = {}
        self._reader_ended_event = None
        self._nursery = nursery 
開發者ID:rethinkdb,項目名稱:rethinkdb-python,代碼行數:13,代碼來源:net_trio.py

示例4: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def __init__(
        self,
        workspace_id: EntryID,
        get_workspace_entry,
        device: LocalDevice,
        local_storage,
        backend_cmds,
        event_bus,
        remote_device_manager,
    ):
        self.workspace_id = workspace_id
        self.get_workspace_entry = get_workspace_entry
        self.device = device
        self.local_storage = local_storage
        self.backend_cmds = backend_cmds
        self.event_bus = event_bus
        self.remote_device_manager = remote_device_manager
        self.sync_locks = defaultdict(trio.Lock)

        self.remote_loader = RemoteLoader(
            self.device,
            self.workspace_id,
            self.get_workspace_entry,
            self.backend_cmds,
            self.remote_device_manager,
            self.local_storage,
        )
        self.transactions = SyncTransactions(
            self.workspace_id,
            self.get_workspace_entry,
            self.device,
            self.local_storage,
            self.remote_loader,
            self.event_bus,
        ) 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:37,代碼來源:workspacefs.py

示例5: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def __init__(self, path, vacuum_threshold=None):
        self._conn = None
        self._lock = trio.Lock()
        self._run_in_thread = None

        self.path = Path(path)
        self.vacuum_threshold = vacuum_threshold 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:9,代碼來源:local_database.py

示例6: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def __init__(
        self,
        device: LocalDevice,
        path: Path,
        workspace_id: EntryID,
        data_localdb: LocalDatabase,
        cache_localdb: LocalDatabase,
        block_storage: ChunkStorage,
        chunk_storage: ChunkStorage,
        manifest_storage: ManifestStorage,
    ):
        self.path = path
        self.device = device
        self.device_id = device.device_id
        self.workspace_id = workspace_id

        # File descriptors
        self.open_fds: Dict[FileDescriptor, EntryID] = {}
        self.fd_counter = 0

        # Locking structures
        self.locking_tasks = {}
        self.entry_locks = defaultdict(trio.Lock)

        # Manifest and block storage
        self.data_localdb = data_localdb
        self.cache_localdb = cache_localdb
        self.manifest_storage = manifest_storage
        self.block_storage = block_storage
        self.chunk_storage = chunk_storage 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:32,代碼來源:workspace_storage.py

示例7: _test_target

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def _test_target(self, fn, **kwargs):
        # Initialize trio objects
        self._lock = trio.Lock()
        self._stopping = trio.Event()
        self._trio_token = trio.hazmat.current_trio_token()

        # Set the started state event
        self._started.set()

        # Run the test
        try:
            result = await self._run_with_job_scheduler(fn, **kwargs)
        except BaseException as exc:
            self._test_result.set_exception(exc)
        else:
            self._test_result.set_result(result)

        # Indicate there will be no more requests
        self._request_queue.put_nowait(None)

        # Let the trio loop run until teardown
        await self._stopping.wait()


# Not an async fixture (and doesn't depend on an async fixture either)
# this fixture will actually be executed *before* pytest-trio setup
# the trio loop, giving us a chance to monkeypatch it ! 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:29,代碼來源:conftest.py

示例8: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def __init__(self,
                 local_private_key: bytes,
                 local_node_id: NodeID,
                 remote_node_id: NodeID,
                 node_db: NodeDBAPI,
                 message_type_registry: MessageTypeRegistry,
                 incoming_packet_receive_channel: ReceiveChannel[IncomingPacket],
                 incoming_message_send_channel: SendChannel[IncomingMessage],
                 outgoing_message_receive_channel: ReceiveChannel[OutgoingMessage],
                 outgoing_packet_send_channel: SendChannel[OutgoingPacket],
                 ) -> None:
        self.local_private_key = local_private_key
        self.local_node_id = local_node_id
        self.remote_node_id = remote_node_id
        self.node_db = node_db
        self.message_type_registry = message_type_registry

        self.incoming_packet_receive_channel = incoming_packet_receive_channel
        self.incoming_message_send_channel = incoming_message_send_channel
        self.outgoing_message_receive_channel = outgoing_message_receive_channel
        self.outgoing_packet_send_channel = outgoing_packet_send_channel

        self.logger = logging.getLogger(
            f"p2p.discv5.packer.PeerPacker[{encode_hex(remote_node_id)[2:10]}]"
        )

        self.outgoing_message_backlog: List[OutgoingMessage] = []

        # This lock ensures that at all times, at most one incoming packet or outgoing message is
        # being processed.
        self.handling_lock = trio.Lock()

        self.handshake_successful_event: Optional[trio.Event] = None 
開發者ID:ethereum,項目名稱:trinity,代碼行數:35,代碼來源:packer.py

示例9: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def __init__(self) -> None:
        self._store: Dict[TickCount, Tuple[Duty, ...]] = defaultdict(tuple)
        self._store_lock = trio.Lock() 
開發者ID:ethereum,項目名稱:trinity,代碼行數:5,代碼來源:duty_store.py

示例10: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def __init__(
        self, genesis_time: int, beacon_node_endpoint: str, seconds_per_slot: int
    ) -> None:
        self._genesis_time = genesis_time
        self._beacon_node_endpoint = _normalize_url(beacon_node_endpoint)
        self._seconds_per_slot = seconds_per_slot
        self._ticks_per_slot = TICKS_PER_SLOT
        self._session = Session()
        self._connection_lock = trio.Lock()
        self._is_connected = False
        self.client_version: Optional[str] = None
        # NOTE: this facilitates testing, may remove in the future...
        self._broadcast_operations: Set[Root] = set() 
開發者ID:ethereum,項目名稱:trinity,代碼行數:15,代碼來源:beacon_node.py

示例11: __init__

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def __init__(
        self,
        device: LocalDevice,
        path: Path,
        backend_cmds: APIV1_BackendAuthenticatedCmds,
        remote_devices_manager: RemoteDevicesManager,
        event_bus: EventBus,
    ):
        self.device = device
        self.path = path
        self.backend_cmds = backend_cmds
        self.remote_devices_manager = remote_devices_manager
        self.event_bus = event_bus

        self.storage = None

        # Message processing is done in-order, hence it is pointless to do
        # it concurrently
        self._workspace_storage_nursery = None
        self._process_messages_lock = trio.Lock()
        self._update_user_manifest_lock = trio.Lock()
        self._workspace_storages = {}

        now = pendulum_now()
        wentry = WorkspaceEntry(
            name="<user manifest>",
            id=device.user_manifest_id,
            key=device.user_manifest_key,
            encryption_revision=1,
            encrypted_on=now,
            role_cached_on=now,
            role=WorkspaceRole.OWNER,
        )
        self.remote_loader = RemoteLoader(
            self.device,
            self.device.user_manifest_id,
            lambda: wentry,
            self.backend_cmds,
            self.remote_devices_manager,
            # Hack, but fine as long as we only call `load_realm_current_roles`
            None,
        ) 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:44,代碼來源:userfs.py

示例12: backend_invited_cmds_factory

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def backend_invited_cmds_factory(
    addr: BackendInvitationAddr, keepalive: Optional[int] = None
) -> AsyncGenerator[BackendInvitedCmds, None]:
    """
    Raises:
        BackendConnectionError
    """
    transport_lock = trio.Lock()
    transport = None
    closed = False

    async def _init_transport():
        nonlocal transport
        if not transport:
            if closed:
                raise trio.ClosedResourceError
            transport = await connect_as_invited(addr, keepalive=keepalive)
            transport.logger = transport.logger.bind(auth="<invited>")

    async def _destroy_transport():
        nonlocal transport
        if transport:
            await transport.aclose()
            transport = None

    @asynccontextmanager
    async def _acquire_transport(**kwargs):
        nonlocal transport

        async with transport_lock:
            await _init_transport()
            try:
                yield transport
            except BackendNotAvailable:
                await _destroy_transport()
                raise

    try:
        yield BackendInvitedCmds(addr, _acquire_transport)

    finally:
        async with transport_lock:
            closed = True
            await _destroy_transport() 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:46,代碼來源:invited.py

示例13: backend_authenticated_cmds_factory

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def backend_authenticated_cmds_factory(
    addr: BackendOrganizationAddr,
    device_id: DeviceID,
    signing_key: SigningKey,
    keepalive: Optional[int] = None,
) -> AsyncGenerator[BackendAuthenticatedCmds, None]:
    """
    Raises:
        BackendConnectionError
    """
    transport_lock = trio.Lock()
    transport = None
    closed = False

    async def _init_transport():
        nonlocal transport
        if not transport:
            if closed:
                raise trio.ClosedResourceError
            transport = await connect_as_authenticated(
                addr, device_id=device_id, signing_key=signing_key, keepalive=keepalive
            )
            transport.logger = transport.logger.bind(device_id=device_id)

    async def _destroy_transport():
        nonlocal transport
        if transport:
            await transport.aclose()
            transport = None

    @asynccontextmanager
    async def _acquire_transport(**kwargs):
        nonlocal transport

        async with transport_lock:
            await _init_transport()
            try:
                yield transport
            except BackendNotAvailable:
                await _destroy_transport()
                raise

    try:
        yield BackendAuthenticatedCmds(addr, _acquire_transport)

    finally:
        async with transport_lock:
            closed = True
            await _destroy_transport() 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:51,代碼來源:authenticated.py

示例14: apiv1_backend_anonymous_cmds_factory

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def apiv1_backend_anonymous_cmds_factory(
    addr: BackendOrganizationAddr, keepalive: Optional[int] = None
) -> AsyncGenerator[APIV1_BackendAnonymousCmds, None]:
    """
    Raises:
        BackendConnectionError
    """
    transport_lock = trio.Lock()
    transport = None
    closed = False

    async def _init_transport():
        nonlocal transport
        if not transport:
            if closed:
                raise trio.ClosedResourceError
            transport = await apiv1_connect(addr, keepalive=keepalive)
            transport.logger = transport.logger.bind(auth="<anonymous>")

    async def _destroy_transport():
        nonlocal transport
        if transport:
            await transport.aclose()
            transport = None

    @asynccontextmanager
    async def _acquire_transport(**kwargs):
        nonlocal transport

        async with transport_lock:
            await _init_transport()
            try:
                yield transport
            except BackendNotAvailable:
                await _destroy_transport()
                raise

    try:
        yield APIV1_BackendAnonymousCmds(addr, _acquire_transport)

    finally:
        async with transport_lock:
            closed = True
            await _destroy_transport() 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:46,代碼來源:apiv1_annonymous.py

示例15: apiv1_backend_authenticated_cmds_factory

# 需要導入模塊: import trio [as 別名]
# 或者: from trio import Lock [as 別名]
def apiv1_backend_authenticated_cmds_factory(
    addr: BackendOrganizationAddr,
    device_id: DeviceID,
    signing_key: SigningKey,
    keepalive: Optional[int] = None,
) -> AsyncGenerator[APIV1_BackendAuthenticatedCmds, None]:
    """
    Raises:
        BackendConnectionError
    """
    transport_lock = trio.Lock()
    transport = None
    closed = False

    async def _init_transport():
        nonlocal transport
        if not transport:
            if closed:
                raise trio.ClosedResourceError
            transport = await apiv1_connect(
                addr, device_id=device_id, signing_key=signing_key, keepalive=keepalive
            )
            transport.logger = transport.logger.bind(device_id=device_id)

    async def _destroy_transport():
        nonlocal transport
        if transport:
            await transport.aclose()
            transport = None

    @asynccontextmanager
    async def _acquire_transport(**kwargs):
        nonlocal transport

        async with transport_lock:
            await _init_transport()
            try:
                yield transport
            except BackendNotAvailable:
                await _destroy_transport()
                raise

    try:
        yield APIV1_BackendAuthenticatedCmds(addr, _acquire_transport)

    finally:
        async with transport_lock:
            closed = True
            await _destroy_transport() 
開發者ID:Scille,項目名稱:parsec-cloud,代碼行數:51,代碼來源:apiv1_authenticated.py


注:本文中的trio.Lock方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。