asyncio 系列五、同步原语—Synchronization Primitives

官网连接:https://docs.python.org/zh-cn/3.7/library/asyncio-sync.html

将 Synchronization Primitives 暂且翻译为同步原语,设计目的是为了和线程模块相似。

 

一、Lock

class asyncio.Lock(*loop=None)

为了实现任务之间的互斥,不是线程安全的。

用于保证独自使用资源。

用with语句:

 

lock = asyncio.Lock()

# ... later
async with lock:
    # access shared state

等价于:

 

lock = asyncio.Lock()

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

acquire() 函数是个协程,使用时需要使用await关键字等待:

原文:

Acquire the lock.

This method waits until the lock is unlocked, sets it to locked and returns True.

release() 函数是个普通函数,如果锁处于unlock状态会报 RuntimeError异常:

原文:

Release the lock.

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

If the lock is unlocked, a RuntimeError is raised

locked() 普通函数

Return True if the lock is locked

二、event

class asyncio.Event(*loop=None)

An event object. Not thread-safe.

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 with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is set to true. The flag is set to false initially.

一个事件对象,非线程安全。

事件对象管理了内部的一个状态,可以通过set方法设置为true,clear方法设置为false。wait方法会等待直到状态为true,在=初始化化的时候是false。

官网实例代码:

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())

coroutine wait() 协程函数,调用时需要用await关键字

Wait until the event is set.

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

set()

Set the event.

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

clear()

Clear (unset) the event.

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

is_set()

Return True if the event is set.

 

三、Condition

class asyncio.Condition(lock=None*loop=None)

A Condition object. Not thread-safe.

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 and a 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.

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

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

一个条件对象,非线程安全。

asyncio的条件原语,可以被一个任务用来等待一些事件发生,然后独自获取资源。

本质上是lock和event对象的功能的结合。可以多个条件对象共享一个锁,这个锁控制某个条件对象去独自获取不同任务之间的共同资源。

lock参数必须是lock或者None,当是None的时候,一个lock对象会随后自动创建。

首选使用方式Conditiond的方法是with语句。

 

cond = asyncio.Condition()

# ... later
async with cond:
    await cond.wait()

 

等价于

 

cond = asyncio.Condition()

# ... later
await lock.acquire()
try:
    await cond.wait()
finally:
    lock.release()

coroutine acquire()

Acquire the underlying lock.

This method waits until the underlying lock is unlocked, sets it to locked and returns True.

协程函数,需要使用await调用,等待将lock设置为unlock状态

 

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.

使用前,需要加锁,使用后,需要释放。

将处于等待状态任务唤醒,n是唤醒的任务的个数。没有任务等待的时候,此函数不起作用。

 

locked()

Return True if the underlying lock is acquired.

判断是否已上锁,如果已上锁,返回True。

 

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.

和notify函数一样,唤醒所有等待的任务,使用前上锁,使用后释放,如果使用前没上锁,会报 RuntimeError 异常。

 

release()

Release the underlying lock.

在未锁定的锁调用时,会引发 RuntimeError 异常。

coroutine wait()

Wait until notified.

If the calling task has not acquired the lock when this method is called, a RuntimeError is raised.

This method releases the underlying lock, and then blocks until it is awakened by a notify() or notify_all() call. Once awakened, the Condition re-acquires its lock and this method returns True.

协程函数,需要用await调用。

将锁释放后,阻塞等待直到通过notify() or notify_all() 函数被唤醒。唤醒后,这个条件对象重新上锁病返回True。

 

coroutine 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.

协程函数,需要使用await调用。

阻塞等待到predicate(暂且翻译为谓词对象)返回true。

 

四、Semaphore

class asyncio.Semaphore(value=1*loop=None)

A Semaphore object. Not thread-safe.

A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some task calls release().

The optional value argument gives the initial value for the internal counter (1 by default). If the given value is less than 0 a ValueError is raised.

信号对象,非线程安全。

信号对象管理加锁次数的计数器,acquire()会减少计数,release会增加计数。如果计数等于0,会等待某任务调用release()。

使用时首选with语句:

 

sem = asyncio.Semaphore(10)

# ... later
async with sem:
    # work with shared resource

等价于:

 

sem = asyncio.Semaphore(10)

# ... later
await sem.acquire()
try:
    # work with shared resource
finally:
    sem.release()

coroutine 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.

协程函数,计数器大于0时,直接将计数器-1,返回True;等于0时会等待release被调用。

 

locked()

Returns 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.

Unlike BoundedSemaphoreSemaphore allows making more release() calls than acquire() calls.

将计数器+1,允许release()的调用多于acquire()。

 

五、BoundedSemaphore

class asyncio.BoundedSemaphore(value=1*loop=None)

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.

 

绑定信号对象,非线程安全。

Semaphore 信号对象的绑定版,release()调用的时候计数器大于初始值会报ValueError异常。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值