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 theclear()
method. Thewait()
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_taskasyncio.run(main())
coroutine wait
() 协程函数,调用时需要用await关键字
Wait until the event is set.
If the event is set, return
True
immediately. Otherwise block until another task callsset()
.
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 theset()
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 aLock
. 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 orNone
. 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()
ornotify_all()
call. Once awakened, the Condition re-acquires its lock and this method returnsTrue
.
协程函数,需要用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 eachrelease()
call. The counter can never go below zero; whenacquire()
finds that it is zero, it blocks, waiting until some task callsrelease()
.The optional value argument gives the initial value for the internal counter (
1
by default). If the given value is less than0
aValueError
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 arelease()
is called and returnTrue
.
协程函数,计数器大于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
BoundedSemaphore
,Semaphore
allows making morerelease()
calls thanacquire()
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 aValueError
inrelease()
if it increases the internal counter above the initial value.
绑定信号对象,非线程安全。
Semaphore 信号对象的绑定版,release()调用的时候计数器大于初始值会报ValueError异常。
asyncio 系列五、同步原语—Synchronization Primitives相关推荐
- asyncio 系列五、asyncio的事件循环
官网连接:https://docs.python.org/zh-cn/3.7/library/asyncio-eventloop.html#asyncio.loop.run_in_executor 事 ...
- Linux同步原语系列-spinlock及其演进优化
1. 引言 通常我们的说的同步其实有两个层面的意思: 一个是线程间的同步,主要是为了按照编程者指定的特定顺序执行: 另外一个是数据的同步,主要是为了保存数据. 为了高效解决同步问题,前人抽象出同步原语 ...
- 线程互斥与同步 在c#中用mutex类实现线程的互斥_Golang 并发编程与同步原语
5.1 同步原语与锁 · 浅谈 Go 语言实现原理draveness.me 当提到并发编程.多线程编程时,我们往往都离不开『锁』这一概念,Go 语言作为一个原生支持用户态进程 Goroutine 的 ...
- Golang 并发编程之同步原语
当提到并发编程.多线程编程时,我们往往都离不开『锁』这一概念,Go 语言作为一个原生支持用户态进程 Goroutine 的语言,也一定会为开发者提供这一功能,锁的主要作用就是保证多个线程或者 Goro ...
- Linux内核中的同步原语:自旋锁,信号量,互斥锁,读写信号量,顺序锁
Linux内核中的同步原语 自旋锁,信号量,互斥锁,读写信号量,顺序锁 rtoax 2021年3月 在英文原文基础上,针对中文译文增加5.10.13内核源码相关内容. 1. Linux 内核中的同步原 ...
- VS 中配置使用Visual SVN系列 五:SVN Client的配置和使用
VS 中配置使用Visual SVN系列 五:SVN Client的配置和使用 1.TortoiseSVN上传项目文件 2.VS中同步该项目文件 到此VS 中配置使用Visual SVN系列已经完成如 ...
- Redis系列(五):Redis的过期键删除策略
Redis系列(五):Redis的过期键删除策略 - 申城异乡人 - 博客园 本篇博客是Redis系列的第5篇,主要讲解下Redis的过期键删除策略. 本系列的前4篇可以点击以下链接查看: Redis ...
- linux kernle 同步原语
转载:同步原语 如何避免由于对共享数据的不安全访问导致的数据崩溃? 内核使用的各种同步技术: 技术 说明 适用范围 每CPU变量 在CPU之间复制数据结构 所有CPU 原子操作 对一个计数器原子地&q ...
- C++11 线程同步原语
本文主要讲述C++11线程同步原语,以及使用场景. C++11 线程同步原语有三个:mutex(互斥锁),condition variable(条件变量)和semaphore(信号量). 一 mute ...
最新文章
- Docker容器的文件系统管理
- 微服务架构的核心要点和实现原理
- Java-集合的简单介绍
- char varchar java_在数据库中varchar与char的区别
- Linux 中文无法显示或显示方块
- c ++向量库_将向量复制到C ++中的另一个向量
- python装饰器模式带参数_Python装饰器使用实例:验证参数合法性 请教Python 使用装饰器实现单例模式的原理...
- js中变量名提升和函数名提升
- caffe+CPU︱虚拟机+Ubuntu16.04+CPU+caffe安装笔记
- caffe 实践程序2——用细分的方法实现caffe中cifar100的识别
- pve万兆网卡驱动_家庭基础万兆网络——最简单的方案
- 认清性能问题,性能问题深入探究----性能之「道」
- java中分号能代表换行吗,go语言中换行和分号那点事------理解为什么
- redis--bugger分析
- 精品文章!精讲光模块的方方面面,收藏!
- 360企业安全校招内推(可免笔试)
- PS轻松制作四种扁平化风格图标
- Pro/E产品设计之绘制齿轮的步骤
- htmlunit 使用代理IP
- python涨跌柱表行业市盈率