这篇文章主要讲解了“怎么理解PostgreSQL Locks中的Fast Path Locking”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么理解PostgreSQL Locks中的Fast Path Locking”吧!

PG提供的系统表pg_locks中有一个字段:fastpath,用以表示是否fastpath,那fastpath指的是什么呢?

一、Fast Path Locking

FastPathLocking-----------------Fastpathlockingisaspecialpurposemechanismdesignedtoreducetheoverheadoftakingandreleasingcertaintypesoflockswhicharetakenandreleasedveryfrequentlybutrarelyconflict.Currently,thisincludestwocategoriesoflocks:Fastpathlocking用以减少那些需要经常获取和释放但又很少出现冲突的锁类型的获取/释放负载.当前的做法,包括2种类型(category)的锁:(1)Weakrelationlocks.SELECT,INSERT,UPDATE,andDELETEmustacquirealockoneveryrelationtheyoperateon,aswellasvarioussystemcatalogsthatcanbeusedinternally.ManyDMLoperationscanproceedinparallelagainstthesametableatthesametime;onlyDDLoperationssuchasCLUSTER,ALTERTABLE,orDROP--orexplicituseractionsuchasLOCKTABLE--willcreatelockconflictswiththe"weak"locks(AccessShareLock,RowShareLock,RowExclusiveLock)acquiredbyDMLoperations.(1)弱关系锁.SELECT,INSERT,UPDATE和DELETE必须在relation上获取锁,这些relation是在内部使用的各种系统目录(数据字典).许多DML操作可同一时间在同一个表上进行并行操作;只有DDL操作,比如CLUSTER,ALTERTABLE,DROP或显示的用户操作如LOCKTABLE会与需要通过DML操作而获得的"weak"锁(AccessShareLock,RowShareLock,RowExclusiveLock)出现冲突.(2)VXIDlocks.EverytransactiontakesalockonitsownvirtualtransactionID.Currently,theonlyoperationsthatwaitfortheselocksareCREATEINDEXCONCURRENTLYandHotStandby(inthecaseofaconflict),somostVXIDlocksaretakenandreleasedbytheownerwithoutanyoneelseneedingtocare.(2)VXID锁.每一个事务都会持有自身虚拟事务ID锁.当前的做法是,等待这些锁的操作只有CREATEINDEXCONCURRENTLY和HotStandby(出现冲突的情况),因此大多数VXID锁跟其他进程无关.Theprimarylockingmechanismdoesnotcopewellwiththisworkload.Eventhoughthelockmanagerlocksarepartitioned,thelocktagforanygivenrelationstillfallsinone,andonlyone,partition.Thus,ifmanyshortqueriesareaccessingthesamerelation,thelockmanagerpartitionlockforthatpartitionbecomesacontentionbottleneck.Thiseffectismeasurableevenon2-coreservers,andbecomesverypronouncedascorecountincreases.主要的锁定机制不能很好的处理这种工作负载.就算锁管理器的locks已分区,对于任意给定的realtion仍会落在其中一个且唯一一个分区上.因此,如果许多端查询正在访问相同的relation,该分区上的锁会成为争用瓶颈.随着CPU核数的升高,这种影响会非常明显.Toalleviatethisbottleneck,beginninginPostgreSQL9.2,eachbackendispermittedtorecordalimitednumberoflocksonunsharedrelationsinanarraywithinitsPGPROCstructure,ratherthanusingtheprimarylocktable.Thismechanismcanonlybeusedwhenthelockercanverifythatnoconflictinglocksexistatthetimeoftakingthelock.为了消除这样的瓶颈,在PG9.2开始,允许每一个后台进程记录非共享relation上有限数目的锁在PGPROC结构体中的数组中,而不是使用主要locktable.该机制只用于在锁定者可以验证没有冲突的情况.AkeypointofthisalgorithmisthatitmustbepossibletoverifytheabsenceofpossiblyconflictinglockswithoutfightingoverasharedLWLockorspinlock.Otherwise,thiseffortwouldsimplymovethecontentionbottleneckfromoneplacetoanother.Weaccomplishthisusinganarrayof1024integercounters,whichareineffecta1024-waypartitioningofthelockspace.Eachcounterrecordsthenumberof"strong"locks(thatis,ShareLock,ShareRowExclusiveLock,ExclusiveLock,andAccessExclusiveLock)onunsharedrelationsthatfallintothatpartition.Whenthiscounterisnon-zero,thefastpathmechanismmaynotbeusedtotakenewrelationlockswithinthatpartition.Astronglockerbumpsthecounterandthenscanseachper-backendarrayformatchingfast-pathlocks;anywhicharefoundmustbetransferredtotheprimarylocktablebeforeattemptingtoacquirethelock,toensureproperlockconflictanddeadlockdetection.该算法的一个关键点是可以验证可能的冲突不会出现,而不需要与共享LWLock或spinlock竞争.否则的话,这样的处理结果会简单的把争用瓶颈从一个地方移到了另外一个地方.我们使用1024个整型计数器数组对应1024个锁空间分区来实现这一点.每一个计数器记录锁分区上非共享relation上"strong"锁(ShareLock,ShareRowExclusiveLock,ExclusiveLock,andAccessExclusiveLock)的数目.如果该计数器非0,则不使用fastpath机制."strong"锁会修改计数器,然后扫描每一个后台进程匹配的fast-pathlocks数组;每一个匹配的都必须在尝试获取lock前转换为主locktable,用以确保正使用确的锁冲突和死锁检测.OnanSMPsystem,wemustguaranteepropermemorysynchronization.HerewerelyonthefactthatLWLockacquisitionactsasamemorysequencepoint:ifAperformsastore,AandBbothacquireanLWLockineitherorder,andBthenperformsaloadonthesamememorylocation,itisguaranteedtoseeA'sstore.Inthiscase,eachbackend'sfast-pathlockqueueisprotectedbyanLWLock.Abackendwishingtoacquireafast-pathlockgrabsthisLWLockbeforeexaminingFastPathStrongRelationLockstocheckforthepresenceofaconflictingstronglock.Andthebackendattemptingtoacquireastronglock,becauseitmusttransferanymatchingweaklockstakenviathefast-pathmechanismtothesharedlocktable,willacquireeveryLWLockprotectingabackendfast-pathqueueinturn.So,ifweexamineFastPathStrongRelationLocksandseeazero,theneitherthevalueistrulyzero,orifitisastalevalue,thestronglockerhasyettoacquiretheper-backendLWLockwenowhold(or,indeed,eventhefirstper-backendLWLock)andwillnoticeanyweaklockwetakewhenitdoes.在SMP系统上,必须确保正确的内存同步.在这里,需要依赖于LWLock获取作为内存序列点这一事实:如果A执行store,A和B按任意顺序获取LWLock,然后B在相同的内存上执行load,这可以确保A'store.在这种情况下,每一个后台进程的fast-path锁会在检查FastPathStrongRelationLocks是否与stronglock存在冲突前获取此LWLock.后台进程试图获取stronglock,因为它必须传输通过fast-path路径获取的匹配weaklocks到共享locktable中,因此将依次获取保护后台进程fast-path的每个LWLock.因此,如果检查FastPathStrongRelationLocks结果为0,那么该值实际真的为0或者是一个固定值,stronglocks必须请求持有的per-backendLWLock,在完成后会关注所有的weaklock.Fast-pathVXIDlocksdonotusetheFastPathStrongRelationLockstable.ThefirstlocktakenonaVXIDisalwaystheExclusiveLocktakenbyitsowner.AnysubsequentlockersaresharelockerswaitingfortheVXIDtoterminate.Indeed,theonlyreasonVXIDlocksusethelockmanageratall(ratherthanwaitingfortheVXIDtoterminateviasomeothermethod)isfordeadlockdetection.Thus,theinitialVXIDlockcan*always*betakenviathefastpathwithoutcheckingforconflicts.Anysubsequentlockermustcheckwhetherthelockhasbeentransferredtothemainlocktable,andifnot,doso.ThebackendowningtheVXIDmustbecarefultocleanupanyentrymadeinthemainlocktableatendoftransaction.Fast-pathVXID锁没有使用FastPathStrongRelationLocks表.在VXID上获取的第一个锁通常是其自身的ExclusiveLock.接下来的lockers是等待VXID结束的共享lockers.实际上,VXID锁只有使用锁管理器的唯一理由是用于死锁检测.因此,VXID的初始化不需要检查冲突而是直接通过fast-path获取.所有后续的locker必须检查锁释放已传输到主locktable中,如没有,则执行此操作.拥有VXID的后台进程必须在事务结束后小心清理主locktable中的entry.Deadlockdetectiondoesnotneedtoexaminethefast-pathdatastructures,becauseanylockthatcouldpossiblybeinvolvedinadeadlockmusthavebeentransferredtothemaintablesbeforehand.死锁检查不需要检查fast-path数据结构,因为所有的锁已传输到maintable中.

感谢各位的阅读,以上就是“怎么理解PostgreSQL Locks中的Fast Path Locking”的内容了,经过本文的学习后,相信大家对怎么理解PostgreSQL Locks中的Fast Path Locking这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!