




已阅读5页,还剩47页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter16 ConcurrencyControl Lock BasedProtocols 基于锁的协议 Timestamp BasedProtocols 基于时间戳的协议 Validation BasedProtocols 基于有效性检查的协议 MultipleGranularity 多粒度 MultiversionSchemes 多版本机制 DeadlockHandling 死锁处理 InsertandDeleteOperations 插入与删除处理 Lock BasedProtocols 基于锁的协议 AlockisamechanismtocontrolconcurrentaccesstoadataitemDataitemscanbelockedintwomodes 1 exclusive排他锁 X mode Dataitemcanbebothreadaswellaswritten X lockisrequestedusinglock Xinstruction 2 shared共享锁 S mode Dataitemcanonlyberead S lockisrequestedusinglock Sinstruction Lockrequestsaremadetoconcurrency controlmanager Transactioncanproceedonlyafterrequestisgranted Lock BasedProtocols Cont Lock compatibilitymatrix 锁相容性矩阵 AtransactionmaybegrantedalockonanitemiftherequestedlockiscompatiblewithlocksalreadyheldontheitembyothertransactionsAnynumberoftransactionscanholdsharedlocksonanitem butifanytransactionholdsanexclusiveontheitemnoothertransactionmayholdanylockontheitem Ifalockcannotbegranted therequestingtransactionismadetowaittillallincompatiblelocksheldbyothertransactionshavebeenreleased Thelockisthengranted Lock BasedProtocols Cont Exampleofatransactionperforminglocking T1 lock X B T2 lock S A read B read A B B 50unlock A write B lock S B unlock B read B lock X A unlock B read A display A B A A 50write A unlock B Lock BasedProtocols Cont T1T2concurrency controlmanagerlock X B grant X B T1 read B B B 50write B unlock B lock S A grant S A T2 read A unlock A lock S B grant S B T2 read B unlock B display A B lock X A grant X A T1 read A A A 50write A unlock B PitfallsofLock BasedProtocols ConsiderthepartialscheduleSuchasituationiscalledadeadlock 死锁 TohandleadeadlockoneofT3orT4mustberolledbackanditslocksreleased PitfallsofLock BasedProtocols Cont Thepotentialfordeadlockexistsinmostlockingprotocols Deadlocksareanecessaryevil Starvation 饿死 isalsopossibleifconcurrencycontrolmanagerisbadlydesigned Forexample T5T6T7T8lock S Q Lock X Q lock S Q unlock Q lock S Q unlock Q unlock Q TheTwo PhaseLockingProtocol 两段锁协议 Thisisaprotocolwhichensuresconflict serializableschedules Phase1 GrowingPhase 增长阶段 transactionmayobtainlockstransactionmaynotreleaselocksPhase2 ShrinkingPhase 缩减阶段 transactionmayreleaselockstransactionmaynotobtainlocksTheprotocolassuresserializability Itcanbeprovedthatthetransactionscanbeserializedintheorderoftheirlockpoints封锁点 i e thepointwhereatransactionacquireditsfinallock TheTwo PhaseLockingProtocol Cont Two phaselockingdoesnotensurefreedomfromdeadlocksCascadingroll backispossibleundertwo phaselocking Toavoidthis followamodifiedprotocolcalledstricttwo phaselocking 严格两段锁 Hereatransactionmustholdallitsexclusivelockstillitcommits aborts Rigoroustwo phaselocking 强两段锁 isevenstricter herealllocksareheldtillcommit abort Inthisprotocoltransactionscanbeserializedintheorderinwhichtheycommit TheTwo PhaseLockingProtocol Cont LockConversions 锁的转换 Two phaselockingwithlockconversions FirstPhase canacquirealock Sonitemcanacquirealock Xonitemcanconvertalock Stoalock X upgrade SecondPhase canreleasealock Scanreleasealock Xcanconvertalock Xtoalock S downgrade Thisprotocolassuresserializability Butstillreliesontheprogrammertoinsertthevariouslockinginstructions LockConversions 锁的转换 Graph BasedProtocols 基于图的协议 Graph basedprotocolsareanalternativetotwo phaselockingImposeapartialordering onthesetD d1 d2 dh ofalldataitems Ifdi djthenanytransactionaccessingbothdianddjmustaccessdibeforeaccessingdj ImpliesthatthesetDmaynowbeviewedasadirectedacyclicgraph calledadatabasegraph Thetree protocolisasimplekindofgraphprotocol TreeProtocol 树形协议 ThefirstlockbyTimaybeonanydataitem Subsequently adataQcanbelockedbyTionlyiftheparentofQiscurrentlylockedbyTi Dataitemsmaybeunlockedatanytime AdataitemthathasbeenlockedandunlockedbyTicannotsubsequentlyberelockedbyTi 加锁指令只有lock X 事务T的首次加锁可以对任何数据项进行 此后 事务T对数据项Q加锁的前提是事务T持有Q的双亲数据项上的锁 对数据项解锁可以随时进行 数据项被事务T加锁并解锁之后 就不能再对该数据项加锁 TreeProtocol TreeProtocol Cont Unlockingmayoccurearlierinthetree lockingprotocolthaninthetwo phaselockingprotocol shorterwaitingtimes andincreaseinconcurrencyprotocolisdeadlock free norollbacksarerequiredHowever inthetree lockingprotocol atransactionmayhavetolockdataitemsthatitdoesnotaccess increasedlockingoverhead andadditionalwaitingtimepotentialdecreaseinconcurrency Timestamp BasedProtocols 基于时间戳的协议 Eachtransactionisissuedatimestampwhenitentersthesystem IfanoldtransactionTihastime stampTS Ti anewtransactionTjisassignedtime stampTS Tj suchthatTS Ti TS Tj Theprotocolmanagesconcurrentexecutionsuchthatthetime stampsdeterminetheserializabilityorder Inordertoassuresuchbehavior theprotocolmaintainsforeachdataQtwotimestampvalues W timestamp Q isthelargesttime stampofanytransactionthatexecutedwrite Q successfully R timestamp Q isthelargesttime stampofanytransactionthatexecutedread Q successfully Timestamp BasedProtocols Cont Thetimestamporderingprotocolensuresthatanyconflictingreadandwriteoperationsareexecutedintimestamporder SupposeatransactionTiissuesaread Q 1 IfTS Ti W timestamp Q thenTineedstoreadavalueofQthatwasalreadyoverwritten Hence thereadoperationisrejected andTiisrolledback 2 IfTS Ti W timestamp Q thenthereadoperationisexecuted andR timestamp Q issettothemaximumofR timestamp Q andTS Ti Timestamp BasedProtocols Cont SupposethattransactionTiissueswrite Q IfTS Ti R timestamp Q thenthevalueofQthatTiisproducingwasneededpreviously andthesystemassumedthatthatvaluewouldneverbeproduced Hence thewriteoperationisrejected andTiisrolledback IfTS Ti W timestamp Q thenTiisattemptingtowriteanobsoletevalueofQ Hence thiswriteoperationisrejected andTiisrolledback Otherwise thewriteoperationisexecuted andW timestamp Q issettoTS Ti ExampleUseoftheProtocol ExampleUseoftheProtocol Apartialscheduleforseveraldataitemsfortransactionswithtimestamps1 2 3 4 5 T1 T2 T3 T4 T5 read Y read X read Y write Y write Z read Z read X read X write Z write Y write Z Thomas WriteRule 托马斯写规则 WhenTiattemptstowritedataitemQ ifTS Ti W timestamp Q thenTiisattemptingtowriteanobsoletevalueof Q Hence ratherthanrollingbackTiasthetimestamporderingprotocolwouldhavedone this write operationcanbeignored Otherwisethisprotocolisthesameasthetimestamporderingprotocol Thomas WriteRuleallowsgreaterpotentialconcurrency Validation BasedProtocol 基于有效性检查的协议 ExecutionoftransactionTiisdoneinthreephases 1 Readphase TransactionTiwritesonlytotemporarylocalvariables2 Validationphase TransactionTiperformsa validationtest todetermineiflocalvariablescanbewrittenwithoutviolatingserializability 3 Writephase IfTiisvalidated theupdatesareappliedtothedatabase otherwise Tiisrolledback Alsocalledasoptimisticconcurrencycontrolsincetransactionexecutesfullyinthehopethatallwillgowellduringvalidation Validation BasedProtocol Cont EachtransactionTihas3timestampsStart Ti thetimewhenTistarteditsexecutionValidation Ti thetimewhenTientereditsvalidationphaseFinish Ti thetimewhenTifinisheditswritephaseSerializabilityorderisdeterminedbytimestampgivenatvalidationtime toincreaseconcurrency ThusTS Ti isgiventhevalueofValidation Ti ScheduleProducedbyValidation Exampleofscheduleproducedusingvalidation T14 T15 read B read B B B 50read A A A 50 read A validate display A B validate write B write A MultipleGranularity 多粒度 Allowdataitemstobeofvarioussizesanddefineahierarchyofdatagranularities wherethesmallgranularitiesarenestedwithinlargeronesCanberepresentedgraphicallyasatree butdon tconfusewithtree lockingprotocol Whenatransactionlocksanodeinthetreeexplicitly itimplicitlylocksallthenode sdescendentsinthesamemode Granularityoflocking levelintreewherelockingisdone finegranularity lowerintree highconcurrency highlockingoverheadcoarsegranularity higherintree lowlockingoverhead lowconcurrency ExampleofGranularityHierarchy Thehighestlevelintheexamplehierarchyistheentiredatabase Thelevelsbelowareoftypearea fileandrecordinthatorder MultiversionSchemes 多版本机制 Multiversionschemeskeepoldversionsofdataitemtoincreaseconcurrency MultiversionTimestampOrderingMultiversionTwo PhaseLockingEachsuccessfulwriteresultsinthecreationofanewversionofthedataitemwritten Usetimestampstolabelversions Whenaread Q operationisissued selectanappropriateversionofQbasedonthetimestampofthetransaction andreturnthevalueoftheselectedversion readsneverhavetowaitasanappropriateversionisreturnedimmediately DeadlockHandling 死锁处理 Considerthefollowingtwotransactions T1 write X T2 write Y write Y write X Schedulewithdeadlock T1 T2 lock XonXwrite X lock XonYwrite X waitforlock XonX waitforlock XonY DeadlockHandling Systemisdeadlockedifthereisasetoftransactionssuchthateverytransactioninthesetiswaitingforanothertransactionintheset Deadlockprevention 死锁预防 protocolsensurethatthesystemwillneverenterintoadeadlockstate MoreDeadlockPreventionStrategies Followingschemesusetransactiontimestampsforthesakeofdeadlockpreventionalone wait die 等待 死亡 scheme non preemptiveoldertransactionmaywaitforyoungeronetoreleasedataitem Youngertransactionsneverwaitforolderones theyarerolledbackinstead atransactionmaydieseveraltimesbeforeacquiringneededdataitemwound wait 受伤 死亡 scheme preemptiveoldertransactionwounds forcesrollback ofyoungertransactioninsteadofwaitingforit Youngertransactionsmaywaitforolderones maybefewerrollbacksthanwait diescheme Deadlockprevention Cont Bothinwait dieandinwound waitschemes arolledbacktransactionsisrestartedwithitsoriginaltimestamp Oldertransactionsthushaveprecedenceovernewerones andstarvationishenceavoided Timeout BasedSchemes atransactionwaitsforalockonlyforaspecifiedamountoftime Afterthat thewaittimesoutandthetransactionisrolledback thusdeadlocksarenotpossiblesimpletoimplement butstarvationispossible Alsodifficulttodeterminegoodvalueofthetimeoutinterval DeadlockDetection Deadlockscanbedescribedasawait forgraph whichconsistsofapairG V E Visasetofvertices allthetransactionsinthesystem Eisasetofedges eachelementisanorderedpairTi Tj IfTi TjisinE thenthereisadirectededgefromTitoTj implyingthatTiiswaitingforTjtoreleaseadataitem WhenTirequestsadataitemcurrentlybeingheldbyTj thentheedgeTiTjisinsertedinthewait forgraph ThisedgeisremovedonlywhenTjisnolongerholdingadataitemneededbyTi Thesystemisinadeadlockstateifandonlyifthewait forgraphhasacycle Mustinvokeadeadlock detectionalgorithmperiodicallytolookforcycles DeadlockDetection Cont Wait forgraphwithoutacycle Wait forgraphwithacycle DeadlockRecovery Whendeadlockisdetected Sometransactionwillhavetorolledback madeavictim tobreakdeadlock Selectthattransactionasvictimthatwillincurminimumcost Rollback determinehowfartorollbacktransactionTotalrollback Abortthetransactionandthenrestartit Moreeffectivetorollbacktransactiononlyasfarasnecessarytobreakdeadlock Starvationhappensifsametransactionisalwayschosenasvictim Includethenumberofrollbacksinthecostfactortoavoidstarvation InsertandDeleteOperations Iftwo phaselockingisused Adeleteoperationmaybeperformedonlyifthetransactiondeletingthetuplehasanexclusivelockonthetupletobedeleted AtransactionthatinsertsanewtupleintothedatabaseisgivenanX modelockonthetuple InsertandDeleteOperations Cont Thetransactionscanningtherelationisreadinginformationthatindicateswhattuplestherelationcontains whileatransactioninsertingatupleupdatesthesameinformation Theinformationshouldbelocked Onesolution Associateadataitemwiththerelation torepresenttheinformationaboutwhattuplestherelationcontains Transactionsscanningtherelationacquireasharedlockinthedataitem Transactionsinsertingordeletingatupleacquireanexclusivelockonthedataitem Note locksonthedataitemdonotconflictwithlocksonindividualtuples Aboveprotocolprovidesverylowconcurrencyforinsertions deletions Indexlockingprotocolsprovidehigherconcurrencywhilepreventingthephantomphenomenon byrequiringlocksoncertainindexbuckets IndexLockingProtocol Everyrelationmusthaveatleastoneindex Accesstoarelationmustbemadeonlythroughoneoftheindicesontherelation AtransactionTithatperformsalookupmustlockalltheindexbucketsthatitaccesses inS mode AtransactionTimaynotinsertatupletiintoarelationrwithoutupdatingallindicestor Timustperformalookuponeveryindextofindallindexbucketsthatcouldhavepossiblycontainedapointertotupleti haditexistedalready andobtainlocksinX modeonalltheseindexbuckets TimustalsoobtainlocksinX modeonallindexbucketsthatitmodifies Therulesofthetwo phaselockingprotocolmustbeobserved WeakLevelsofConsistency Degree twoconsistency differsfromtwo phaselockinginthatS locksmaybereleasedatanytime andlocksmaybeacquiredatanytimeX locksmustbeheldtillendoftransactionSerializabilityisnotguaranteed programmermustensurethatnoerroneousdatabasestatewilloccur Cursorstability Forreads eachtupleislocked read andlockisimmediatelyreleasedX locksareheldtillendoftransactionSpecialcaseofdegree twoconsistency WeakLevelsofConsistencyinSQL SQLallowsnon serializableexecutionsSerializable isthedefaultRepeatableread allowsonlycommittedrecordstoberead andrepeatingareadshouldreturnthesamevalue soreadlocksshouldberetained However thephantomphenomenonneednotbepreventedT1mayseesomerecordsinsertedbyT2 butmaynotseeothersinsertedbyT2Readcommitted sameasdegreetwoconsistency butmostsystemsimplementitascursor stabilityReaduncommitted allowsevenuncommitteddatatoberead ConcurrencyinIndexStructures Indicesareunlikeother
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 广东管理学原理中级自考试题及答案
- 了解中医考试题及答案
- 广东法律自考试题及答案
- 控制原理考试题及答案
- 客舱清洁考试题及答案
- 铝电解综合工主管竞选考核试卷及答案
- 带式球团焙烧工入职考核试卷及答案
- 中药合剂工专项考核试卷及答案
- 押题宝典教师招聘之《小学教师招聘》通关考试题库1套附答案详解
- 钽钠还原火法冶炼工理论知识考核试卷及答案
- 友善主题班会课件
- 自动喷灌设计说明及安装大样
- 杭州市“教坛新秀”理论考试简答题汇总
- 2018年全国成人高考专升本政治试题答案
- 人教版(2019)必修三 Unit 3 Diverse Cultures Listening and Talking课件
- 医养结合机构服务质量评价标准(二级医养结合机构)
- 三年级上册数学课件-4.2 两、三位数除以一位数的笔算丨苏教版 (共34张PPT)
- 卡西欧PRO-TREK-PRW-6000使用手册-基础操作
- 建筑结构试验知识点总结
- 2022年公路工程竣交工验收办法实施细则范文
- 日本川崎市武藏小杉格林木(GrandTree)创新型购物中心调研分析报告课件
评论
0/150
提交评论