内容表

  • 同步原语
    • 锁
    • 事件
    • 条件
    • 信号量
    • BoundedSemaphore
    • 就业培训     下载中心     Wiki     联络
      登录   注册

      Log
      1. 首页
      2. Python 3.12.4
      3. 索引
      4. 模块
      5. 下一
      6. 上一
      7. Python 标准库
      8. 网络和进程间通信
      9. asyncio — 异步 I/O
      10. 同步原语

      同步原语 ¶

      源代码: Lib/asyncio/locks.py


      asyncio 同步原语的设计类似那些在 threading 模块有 2 个重要告诫:

      • asyncio 原语不是线程安全的,因此,它们不应用于 OS 线程同步 (使用 threading 为此);

      • 这些同步原语的方法不接受 timeout 自变量;使用 asyncio.wait_for() 函数采用超时履行操作。

      asyncio 拥有下列基本同步原语:

      • Lock

      • Event

      • Condition

      • Semaphore

      • BoundedSemaphore

      • Barrier


      锁 ¶

      class asyncio. 锁 ¶

      为 asyncio 任务实现互斥锁。不是线程安全的。

      An asyncio lock can be used to guarantee exclusive access to a shared resource.

      The preferred way to use a Lock is an async with 语句:

      lock = asyncio.Lock()
      # ... later
      async with lock:
          # access shared state
      															

      which is equivalent to:

      lock = asyncio.Lock()
      # ... later
      await lock.acquire()
      try:
          # access shared state
      finally:
          lock.release()
      															

      3.10 版改变: 移除 loop 参数。

      协程 acquire ( ) ¶

      获得锁。

      This method waits until the lock is unlocked , sets it to locked 并返回 True .

      When more than one coroutine is blocked in acquire() waiting for the lock to be unlocked, only one coroutine eventually proceeds.

      Acquiring a lock is fair : the coroutine that proceeds will be the first coroutine that started waiting on the lock.

      release ( ) ¶

      释放锁。

      When the lock is locked , reset it to unlocked and return.

      If the lock is unlocked , RuntimeError 被引发。

      locked ( ) ¶

      返回 True 若锁 locked .

      事件 ¶

      class asyncio. 事件 ¶

      事件对象。不是线程安全的。

      An asyncio event can be used to notify multiple asyncio tasks that some event has happened.

      An Event object manages an internal flag that can be set to true 采用 set() method and reset to false 采用 clear() 方法。 wait() method blocks until the flag is set to true . The flag is set to false initially.

      3.10 版改变: 移除 loop 参数。

      范例:

      async def waiter(event):
          print('waiting for it ...')
          await event.wait()
          print('... got it!')
      async def main():
          # Create an Event object.
          event = asyncio.Event()
          # Spawn a Task to wait until 'event' is set.
          waiter_task = asyncio.create_task(waiter(event))
          # Sleep for 1 second and set the event.
          await asyncio.sleep(1)
          event.set()
          # Wait until the waiter task is finished.
          await waiter_task
      asyncio.run(main())
      															
      协程 wait ( ) ¶

      等待直到事件被设置。

      If the event is set, return True immediately. Otherwise block until another task calls set() .

      set ( ) ¶

      设置事件。

      All tasks waiting for event to be set will be immediately awakened.

      clear ( ) ¶

      清零 (未设置) 事件。

      Tasks awaiting on wait() will now block until the set() method is called again.

      is_set ( ) ¶

      返回 True 若事件有设置。

      条件 ¶

      class asyncio. 条件 ( lock = None ) ¶

      条件对象。不是线程安全的。

      An asyncio condition primitive can be used by a task to wait for some event to happen and then get exclusive access to a shared resource.

      In essence, a Condition object combines the functionality of an Event 和 Lock . It is possible to have multiple Condition objects share one Lock, which allows coordinating exclusive access to a shared resource between different tasks interested in particular states of that shared resource.

      可选 lock argument must be a Lock object or None . In the latter case a new Lock object is created automatically.

      3.10 版改变: 移除 loop 参数。

      The preferred way to use a Condition is an async with 语句:

      cond = asyncio.Condition()
      # ... later
      async with cond:
          await cond.wait()
      															

      which is equivalent to:

      cond = asyncio.Condition()
      # ... later
      await cond.acquire()
      try:
          await cond.wait()
      finally:
          cond.release()
      															
      协程 acquire ( ) ¶

      Acquire the underlying lock.

      This method waits until the underlying lock is unlocked , sets it to locked 并返回 True .

      notify ( n = 1 ) ¶

      Wake up at most n tasks (1 by default) waiting on this condition. The method is no-op if no tasks are waiting.

      The lock must be acquired before this method is called and released shortly after. If called with an unlocked lock a RuntimeError error is raised.

      locked ( ) ¶

      返回 True if the underlying lock is acquired.

      notify_all ( ) ¶

      Wake up all tasks waiting on this condition.

      This method acts like notify() , but wakes up all waiting tasks.

      The lock must be acquired before this method is called and released shortly after. If called with an unlocked lock a RuntimeError error is raised.

      release ( ) ¶

      Release the underlying lock.

      当在解锁锁援引时, RuntimeError 被引发。

      协程 wait ( ) ¶

      Wait until notified.

      If the calling task has not acquired the lock when this method is called, a RuntimeError 被引发。

      此方法释放底层锁,然后阻塞直到被唤醒由 notify() or notify_all() call. Once awakened, the Condition re-acquires its lock and this method returns True .

      协程 wait_for ( predicate ) ¶

      Wait until a predicate becomes true .

      The predicate must be a callable which result will be interpreted as a boolean value. The final value is the return value.

      信号量 ¶

      class asyncio. 信号量 ( value = 1 ) ¶

      A Semaphore object. Not thread-safe.

      信号量管理的内部计数器的递减是通过每 acquire() 调用和递增是通过每 release() 调用。计数器可以从不低于 0;当 acquire() finds that it is zero, it blocks, waiting until some task calls release() .

      可选 value argument gives the initial value for the internal counter ( 1 by default). If the given value is less than 0 a ValueError 被引发。

      3.10 版改变: 移除 loop 参数。

      The preferred way to use a Semaphore is an async with 语句:

      sem = asyncio.Semaphore(10)
      # ... later
      async with sem:
          # work with shared resource
      															

      which is equivalent to:

      sem = asyncio.Semaphore(10)
      # ... later
      await sem.acquire()
      try:
          # work with shared resource
      finally:
          sem.release()
      															
      协程 acquire ( ) ¶

      获得信号量。

      If the internal counter is greater than zero, decrement it by one and return True immediately. If it is zero, wait until a release() is called and return True .

      locked ( ) ¶

      返回 True if semaphore can not be acquired immediately.

      release ( ) ¶

      Release a semaphore, incrementing the internal counter by one. Can wake up a task waiting to acquire the semaphore.

      不像 BoundedSemaphore , Semaphore allows making more release() calls than acquire() 调用。

      BoundedSemaphore ¶

      class asyncio. BoundedSemaphore ( value = 1 ) ¶

      A bounded semaphore object. Not thread-safe.

      Bounded Semaphore is a version of Semaphore that raises a ValueError in release() if it increases the internal counter above the initial value .

      3.10 版改变: 移除 loop 参数。

      屏障 ¶

      class asyncio. 屏障 ( parties ) ¶

      A barrier object. Not thread-safe.

      A barrier is a simple synchronization primitive that allows to block until parties number of tasks are waiting on it. Tasks can wait on the wait() method and would be blocked until the specified number of tasks end up waiting on wait() . At that point all of the waiting tasks would unblock simultaneously.

      async with can be used as an alternative to awaiting on wait() .

      The barrier can be reused any number of times.

      范例:

      async def example_barrier():
         # barrier with 3 parties
         b = asyncio.Barrier(3)
         # create 2 new waiting tasks
         asyncio.create_task(b.wait())
         asyncio.create_task(b.wait())
         await asyncio.sleep(0)
         print(b)
         # The third .wait() call passes the barrier
         await b.wait()
         print(b)
         print("barrier passed")
         await asyncio.sleep(0)
         print(b)
      asyncio.run(example_barrier())
      															

      Result of this example is:

      <asyncio.locks.Barrier object at 0x... [filling, waiters:2/3]>
      <asyncio.locks.Barrier object at 0x... [draining, waiters:0/3]>
      barrier passed
      <asyncio.locks.Barrier object at 0x... [filling, waiters:0/3]>
      															

      Added in version 3.11.

      协程 wait ( ) ¶

      Pass the barrier. When all the tasks party to the barrier have called this function, they are all unblocked simultaneously.

      When a waiting or blocked task in the barrier is cancelled, this task exits the barrier which stays in the same state. If the state of the barrier is “filling”, the number of waiting task decreases by 1.

      The return value is an integer in the range of 0 to parties-1 , different for each task. This can be used to select a task to do some special housekeeping, e.g.:

      ...
      async with barrier as position:
         if position == 0:
            # Only one task prints this
            print('End of *draining phase*')
      																	

      此方法可能引发 BrokenBarrierError exception if the barrier is broken or reset while a task is waiting. It could raise a CancelledError if a task is cancelled.

      协程 reset ( ) ¶

      Return the barrier to the default, empty state. Any tasks waiting on it will receive the BrokenBarrierError 异常。

      If a barrier is broken it may be better to just leave it and create a new one.

      协程 abort ( ) ¶

      把屏障置于中断状态。这会导致任何活动或未来调用 wait() 失败采用 BrokenBarrierError . Use this for example if one of the tasks needs to abort, to avoid infinite waiting tasks.

      parties ¶

      The number of tasks required to pass the barrier.

      n_waiting ¶

      The number of tasks currently waiting in the barrier while filling.

      broken ¶

      布尔为 True 若屏障处于中断状态。

      exception asyncio. BrokenBarrierError ¶

      此异常是子类化的 RuntimeError ,被引发当 Barrier 对象被重置或中断。


      3.9 版改变: Acquiring a lock using await lock or yield from lock and/or with statement ( with await lock , with (yield from lock) ) was removed. Use async with lock 代替。

      内容表

      • 同步原语
        • 锁
        • 事件
        • 条件
        • 信号量
        • BoundedSemaphore
        • 屏障

      上一话题

      流

      下一话题

      子进程

      本页

      • 报告 Bug
      • 展示源

      快速搜索

      键入搜索术语或模块、类、函数名称。

      1. 首页
      2. Python 3.12.4
      3. 索引
      4. 模块
      5. 下一
      6. 上一
      7. Python 标准库
      8. 网络和进程间通信
      9. asyncio — 异步 I/O
      10. 同步原语

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1