Tải bản đầy đủ - 0 (trang)
Chapter 8. The ACE Proactor Framework

Chapter 8. The ACE Proactor Framework

Tải bản đầy đủ - 0trang

8.1Overview

Chapter3describedtheACEReactorframework,whichismost

oftenusedwithareactiveI/Omodel.Anapplicationbasedon

thismodelregisterseventhandlerobjectsthatarenotifiedbya

reactorwhenit'spossibletoperformoneormoredesiredI/O

operations,suchasreceivingdataonasocket,withahigh

likelihoodofimmediatecompletion.I/Ooperationsareoften

performedinasinglethread,drivenbythereactor'sevent

dispatchingloop.AlthoughreactiveI/Oisacommon

programmingmodel,eachthreadcanexecuteonlyoneI/O

operationatatime.ThesequentialnatureoftheI/Ooperations

canbeabottlenecksinceapplicationsthattransferlarge

amountsofdataonmultipleendpointscan'tusetheparallelism

availablefromtheOSand/ormultipleCPUsornetwork

interfaces.

OnewaytoalleviatethebottlenecksofreactiveI/Oistouse

synchronousI/Oinconjunctionwithamultithreadingmodel,

suchasthethreadpoolmodelinChapter6orthethread-perconnectionmodelinChapter7.Multithreadingcanhelp

parallelizeanapplication'sI/Ooperationsandmayimprove

performance.However,addingmultiplethreadstoadesign

requiresappropriatesynchronizationmechanismstoavoid

concurrencyhazards,suchasraceconditionsanddeadlocks

[Tan92].Theseadditionalconsiderationsrequireexpertisein

concurrencyandsynchronizationtechniques.Theyalsoadd

complexitytobothdesignandcode,increasingtheriskof

subtledefects.Moreover,multithreadingcanincurnon-trivial

time/spaceoverheadduetotheresourcesneededtoallocate

run-timestacks,performcontextswitches[SS95b],andmove

databetweenCPUcaches[SKT96].

AproactiveI/Omodelisoftenamorescalablewaytoalleviate

reactiveI/Obottleneckswithoutintroducingthecomplexityand

overheadofsynchronousI/Oandmultithreading.Thismodel



allowsanapplicationtoexecuteI/Ooperationsviathefollowing

twophases:

1. Theapplicationcaninitiateoneormore

asynchronousI/OoperationsonmultipleI/Ohandles

inparallelwithouthavingtowaituntiltheycomplete.

Aseachoperationcompletes,theOSnotifiesanapplicationdefinedcompletionhandlerthatthenprocessestheresultsfrom

thecompletedI/Ooperation.

ThetwophasesoftheproactiveI/Omodelareessentiallythe

inverseofthoseinthereactiveI/Omodel,inwhichan

application

1. Usesaneventdemultiplexertodeterminewhenan

I/Ooperationispossible,andlikelytocomplete

immediately,andthen

Performstheoperationsynchronously

Inadditiontoimprovingapplicationscalabilityviaasynchrony,

theproactiveI/Omodelcanofferotherbenefits,dependingon

theplatform'simplementationofasynchronousI/O.For

example,ifmultipleasynchronousI/Ooperationscanbe

initiatedsimultaneouslyandeachoperationcarriesextended

information,suchasfilepositionsforfileI/O,theOScan

optimizeitsinternalbufferingstrategytoavoidunnecessary

datacopies.ItcanalsooptimizefileI/Operformanceby

reorderingoperationstominimizediskheadmovementand/or

increasecachehitrates.

TheACEProactorframeworksimplifiesthedevelopmentof

programsthatusetheproactiveI/Omodel.Inthiscontext,the

ACEProactorframeworkisresponsiblefor

InitiatingasynchronousI/Ooperations



Savingeachoperation'sargumentsandrelayingthemto

thecompletionhandler

Waitingforcompletioneventsthatindicatetheseoperations

havefinished

Demultiplexingthecompletioneventstotheirassociated

completionhandlersand

Dispatchingtohookmethodsonthehandlerstoprocessthe

eventsinanapplication-definedmanner

InadditiontoitsI/O-relatedcapabilities,theACEProactor

frameworkoffersthesametimerqueuemechanismsofferedby

theACEReactorframeworkinSection3.4.

ThischapterdescribesthefollowingACEProactorframework

classes:



ACEClass



ACE_Handler



Description



Definestheinterfaceforreceivingtheresultsof

asynchronousI/Ooperationsandhandlingtimer

expirations.



ACE_Asynch_Read_Stream InitiateasynchronousreadandwriteoperationsonanI/O

streamandassociateeachwithanACE_Handlerobject

ACE_Asynch_Write_Stream thatwillreceivetheresultsofthoseoperations.

ACE_Asynch_Result

ACE_Asynch_Acceptor



AnimplementationoftheAcceptor-Connectorpatternthat

establishesnewTCP/IPconnectionsasynchronously.



ACE_Asynch_Connector

ACE_Service_Handler



DefinesthetargetoftheACE_Asynch_Acceptorand

ACE_Asynch_Connectorconnectionfactoriesand

providesthehookmethodstoinitializeaTCP/IP-connected



service.



ACE_Proactor



ManagestimersandasynchronousI/Ocompletionevent

demultiplexing.Thisclassisanalogoustothe

ACE_ReactorclassintheACEReactorframework.



Themostimportantrelationshipsbetweentheclassesinthe

ACEProactorframeworkareshowninFigure8.1(page260).

Theseclassesplaythefollowingrolesinaccordancewiththe

Proactorpattern[POSA2]:

Figure8.1.TheACEProactorFrameworkClasses



AsynchronousI/Oinfrastructurelayerclassesperform

application-independentstrategiesthatinitiate

asynchronousI/Ooperations,demultiplexcompletion

eventstotheircompletionhandlers,andthendispatchthe

associatedcompletionhandlerhookmethods.The

infrastructurelayerclassesintheACEProactorframework

includeACE_Asynch_Acceptor,

ACE_Asynch_Connector,ACE_Asynch_Result,

ACE_Asynch_Read_Stream,



ACE_Asynch_Write_Stream,andvariousimplementations

ofACE_Proactor.Theinfrastructurelayeralsousesthe

ACE_Time_ValueandACEtimerqueueclassesfrom

Sections3.2and3.4.

Applicationlayerclassesincludecompletionhandlers

thatperformapplication-definedprocessingintheirhook

methods.IntheACEProactorframework,theseclassesare

descendantsofACE_Handlerand/or

ACE_Service_Handler.

ThepoweroftheACEProactorframeworkcomesfromthe

separationofconcernsbetweenitsinfrastructureclassesand

applicationclasses.Bydecouplingcompletiondemultiplexing

anddispatchingmechanismsfromapplication-definedevent

processingpolicies,theACEProactorframeworkprovidesthe

followingbenefits:

Improveportability.Applicationscantakeadvantageof

theproactiveI/Omodelonmanyplatformsthathave

diverseasynchronousI/Omechanisms.Itusesoverlapped

I/OonWindows(requiresWindowsNTversion4.0and

higher)andtheAsynchronousI/O(AIO)optionofthe

POSIX.4RealtimeExtensionstandard[POS95]onplatforms

thatimplementit,includingHP-UX,IRIX,Linux,LynxOS,

andSolaris.

Automatescompletiondetection,demultiplexing,and

dispatching.TheACEProactorframeworkisolatesnative

OSI/OinitiationandcompletiondemultiplexingAPIs,as

wellastimersupport,ininfrastructurelayerframework

classes.Applicationscanusetheseobject-oriented

mechanismstoinitiateasynchronousoperations,andonly

needtoimplementapplication-definedcompletionhandlers.



Supporttransparentextensibility.AsshowninSection

8.5,theACEProactorframeworkusestheBridgepattern

[GoF]toexportaninterfacewithuniform,well-defined

behavior.Thisdesignallowstheframeworkinternalsto

changeandadapttovaryingOS-providedasynchronousI/O

implementationsandshortcomingswithoutrequiringany

application-layerchanges.

Increasereuseandminimizeerror-prone

programmingdetails.ByseparatingasynchronousI/O

mechanismsfromapplication-definedpoliciesandbehavior,

theACEProactorframeworkcanbereusedacrossmany

diverseapplicationdomains.

Threadsafety.ApplicationscanuseI/Oparallelismoffered

bytheOSplatformwithoutneedingcomplicated

application-levelsynchronizationstrategies.When

applicationoperationinitiationandcompletionhandling

codeisprocessedinasinglethread,thereareonlysimple

dataaccessrulestofollow,suchas"don'tmanipulatea

bufferthat'sbeengiventotheOSforI/ObeforethatI/Ois

complete."

TheACEProactorframeworkisawhiteboxframeworksince

networkedapplicationeventhandlersmustdescendfrom

ACE_Handler,similartotheACEReactorframework.

Thefollowingsectionsmotivateanddescribethecapabilitiesof

eachclassintheACEProactorframework.Theyalsoillustrate

howthisframeworkcanbeusedtoapplyasynchronousI/Oto

ourclientloggingdaemon.Ifyouaren'tfamiliarwiththe

ProactorpatternfromPOSA2,werecommendthatyouread

aboutitfirstbeforedelvingintothedetailedexamplesinthis

chapter.



8.2TheAsynchronousI/OFactoryClasses

Motivation

TheproactiveI/Omodelisgenerallyhardertoprogramthan

reactiveandsynchronousI/Omodelsbecause

I/Oinitiationandcompletionaredistinctactivitiesthatmust

behandledseparately.

MultipleI/Ooperationscanbeinitiatedsimultaneously,

whichrequiresmorerecordkeeping.

There'snoguaranteedcompletionorderwhenmultipleI/O

operationscompletesimultaneously.

Inamultithreadedserviceacompletionhandlermay

executeinathreadotherthantheonethatinitiatedtheI/O

operation.

TheproactiveI/Omodelthereforerequiresafactorytoinitiate

asynchronousI/Ooperations.SincemultipleI/Ooperationscan

executesimultaneouslyandcompleteinanyorder,the

proactivemodelalsorequiresanexplicitbindingbetweeneach

asynchronousoperation,itsparameters(suchastheI/O

handle,databuffer,andbuffersize),andthecompletion

handlerthatwillprocesstheresultsoftheoperation.

Intheory,designingclassestogenerateasynchronousI/O

operationsandbindthemtotheircompletionhandlersshould

berelativelystraightforward.Inpractice,however,thedesignis

complicatedbythefactthatasynchronousI/Oisimplemented

indifferentwaysacrosstoday'spopularOSplatforms.Two

commonexamplesinclude:



Windows.TheWindowsReadFile()andWriteFile()

systemfunctionscaneitherperformsynchronousI/Oor

initiateanoverlappedI/Ooperation.

POSIX.ThePOSIXaio_read()andaio_write()

functionsinitiateasynchronousreadandwriteoperations,

respectively.Thesefunctionsareseparatefromtheread()

andwrite()(andSocketsrecv()andsend())functions

thatareusedinACE'sIPCwrapperfacadeclasses(see

Chapter3inC++NPv1).

Eachplatform'sasynchronousI/Ofacilityalsoincludesitsown

mechanismforbindinganI/Ooperationwithitsparameters,

suchasbufferpointerandtransfersize.Forexample,POSIX

AIOprovidesanAIOcontrolblock(aiocb),whereasWindows

providestheOVERLAPPEDstructureandacompletionkey

argumenttotheI/Ocompletionportfacility.Sidebar54

discussesotherchallengeswithOSasynchronousI/O

mechanisms.



Sidebar54:AsynchronousI/OPortabilityIssues

UnlikesynchronousI/OandreactiveI/O,whichareavailableonmostmodern

operatingsystems,asynchronousI/Oisnotubiquitous.ThefollowingOS

platformssupportedbyACEprovideasynchronousI/Omechanisms:

WindowsplatformsthatsupportbothoverlappedI/OandI/Ocompletion

ports[Ric97].OverlappedI/OisanefficientandscalableI/Omechanism

onWindows[Sol98].Windowsperformscompletioneventdemultiplexing

viaI/Ocompletionportsandeventhandles.AnI/Ocompletionportisa

queuemanagedbytheWindowskerneltobufferI/Ocompletionevents.

POSIXplatformsthatimplementthePOSIX.4AIOspecification[POS95].

ThisspecificationwasoriginallydesignedfordiskfileI/O[Gal95],butcan

alsobeusedfornetworkI/Owithvaryingdegressofsuccess.An

applicationthreadcanwaitforcompletioneventsviaaio_suspend()or

benotifiedbyreal-timesignals,whicharetrickytointegrateintoaneventdrivenapplication.Ingeneral,POSIX.4AIOrequiresextracaretoprogram

theproactivemodelcorrectlyandefficiently.DespiteUNIX'susual

interchangeabilityofI/OsystemfunctionsacrossIPCmechanisms,

integrationofthePOSIXAIOfacilitywithotherIPCmechanisms,suchas

theSocketAPI,leavesmuchtobedesiredonsomeplatforms.For

example,SocketAPIfunctionssuchasconnect()andaccept()arenot

integratedwiththePOSIXAIOmodel,andsomeAIOimplementationscan't

handlemultipleoutstandingoperationsonahandleunderallconditions.

AsynchronousI/Operformancecharacteristicscanalsovarywidely.Forexample,

someoperatingsystemsimplementthePOSIXAIOfunctionsbyspawninga

threadforeachasynchronousI/Ooperation.Althoughthisisacompliant

implementation,itprovidesnoperformancegainrelativetoanapplication

spawningthethreaditself.Infact,thisimplementationcanactuallydegradethe

performanceofI/O-intensiveapplicationsratherthanimproveit!Hopefully,OS

asynchronousI/Oimplementationswillsoonimprove,allowingwideruseofthis

powerfulmechanism.



AlltheasynchronousI/Omechanismsdiscussedaboveusean

I/OhandletorefertotheIPCchannelorfileonwhichto

performtheI/O.TheACEProactorframeworkdefinesasetof

classesthatinitiateasynchronousI/OonvariousIPC

mechanisms.Theseclassesenhanceportability,minimize

complexity,andavoidreintroducingtheI/Ohandle-related

problemsmasteredinC++NPv1.Thisbookexaminesthetwo

mostpopularclassesfornetworkedapplications,

ACE_Asynch_Read_Streamand



ACE_Asynch_Write_Stream.



ClassCapabilities

ACE_Asynch_Read_StreamandACE_Asynch_Write_Stream

arefactoryclassesthatenableapplicationstoinitiateportable

asynchronousread()andwrite()operations,respectively.

Theseclassesprovidethefollowingcapabilities:

TheycaninitiateasynchronousI/OoperationsonastreamorientedIPCmechanism,suchasaTCPsocket.

TheybindanI/Ohandle,anACE_Handlerobject,andan

ACE_ProactortoprocessI/Ocompletioneventscorrectly

andefficiently.

Theycreateanobjectthatcarriesanoperation's

parametersthroughtheACEProactorframeworktoits

completionhandler.

TheyderivefromACE_Asynch_Operation,whichprovides

theinterfacetoinitializetheobjectandtorequest

cancellationofoutstandingI/Ooperations.



ACE_Asynch_Read_StreamandACE_Asynch_Write_Stream

definenestedResultclassestorepresentthebindingbetween

anoperationanditsparameters.TheACEProactorframework

abstractscommonresults-orientedbehaviorintothe

ACE_Asynch_ResultclassfromwhichthenestedResult

classesderive.Together,thissetofclassesprovidesa

completionhandlerwiththefollowingcapabilities:

ItcanobtaintheoriginalparametersforanI/Ooperation,

suchastherequestedtransferbytecountandthememory



address.

Itcandeterminethesuccessorfailureoftheassociated

operation.

Itcanbepassedanasynchronouscompletiontoken(ACT)

[POSA2]thatprovidesamethodtoextendtheamountand

typeofinformationcommunicatedbetweentheoperation

initiatorandthecompletionhandler.

TheinterfacesforACE_Asynch_Result,

ACE_Asynch_Read_Stream,ACE_Asynch_Write_Stream

andtheirResultnestedclassesareshowninFigure8.2(page

264).Thefollowingtableliststhekeymethodsin

ACE_Asynch_Read_Stream:

Figure8.2.TheACEAsynchronousRead/WriteStream

ClassRelationships



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 8. The ACE Proactor Framework

Tải bản đầy đủ ngay(0 tr)

×