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

Chapter 3. The ACE Reactor Framework

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

3.1Overview

TheACEReactorframeworksimplifiesthedevelopmentof

event-drivenprograms,whichcharacterizemanynetworked

applications.Commonsourcesofeventsintheseapplications

includeactivityonanIPCstreamforI/Ooperations,POSIX

signals,Windowshandlesignaling,andtimerexpirations.In

thiscontext,theACEReactorframeworkisresponsiblefor

Detectingtheoccurrenceofeventsfromvariousevent

sources

Demultiplexingtheeventstotheirpreregisteredevent

handlers

Dispatchingtohookmethodsdefinedbythehandlersto

processtheeventsinanapplication-definedmanner

ThischapterdescribesthefollowingACEReactorframework

classesthatnetworkedapplicationscanusetodetectthe

occurrenceofeventsandthendemultiplexanddispatchthe

eventstotheireventhandlers:

ACEClass



ACE_Time_Value



Description



Providesaportable,normalizedrepresentationoftimeand

durationthatusesC++operatoroverloadingtosimplifytimerelatedarithmeticandrelationaloperations.



ACE_Event_Handler Anabstractclasswhoseinterfacedefinesthehookmethodsthat

arethetargetofACE_Reactorcallbacks.Mostapplicationevent

handlersdevelopedwithACEaredescendantsof

ACE_Event_Handler.



ACE_Timer_Queue



Anabstractclassdefiningthecapabilitiesandinterfaceforatimer

queue.ACEcontainsavarietyofclassesderivedfrom



ACE_Timer_Queuethatprovideflexiblesupportfordifferent

timingrequirements.



ACE_Reactor



Providestheinterfaceformanagingeventhandlerregistrations

andexecutingtheeventloopthatdriveseventdetection,

demultiplexing,anddispatchingintheReactorframework.



Themostimportantrelationshipsbetweentheclassesinthe

ACEReactorframeworkareshowninFigure3.1.Theseclasses

playthefollowingrolesinaccordancewiththeReactorpattern

[POSA2]:

Figure3.1.TheACEReactorFrameworkClasses



Eventinfrastructurelayerclassesprovideapplicationindependentstrategiesforsynchronouslydetectingand

demultiplexingeventstoeventhandlersandthen

dispatchingtheassociatedeventhandlerhookmethods.

TheinfrastructurelayercomponentsintheACEReactor

frameworkincludeACE_Time_Value,

ACE_Event_Handler,theACEtimerqueueclasses,and

thevariousimplementationsoftheACE_Reactor.

Applicationlayerclassesdefineeventhandlersto

performapplication-definedprocessingintheirhook

methods.IntheACEReactorframework,applicationlayer

classesaredescendantsofACE_Event_Handler.

ThepoweroftheACEReactorframeworkcomesfrom



encapsulatingthedifferencesbetweeneventdemultiplexing

mechanismsavailableonvariousoperatingsystemsand

maintainingaseparationofconcernsbetweenframework

classesandapplicationclasses.Byseparatingapplicationindependenteventdemultiplexinganddispatchingmechanisms

fromapplication-dependenteventprocessingpolicies,theACE

Reactorframeworkprovidesthefollowingbenefits:

Broadportability.Theframeworkcanbeconfiguredto

usemanyOSeventdemultiplexingmechanisms,suchas

select()(availableonUNIX,Windows,andmanyrealtimeoperatingsystems),/dev/poll(availableoncertain

UNIXplatforms),andWaitForMultipleObjects()

(availableonlyonWindows).

Automateseventdetection,demultiplexing,and

dispatching.Byeliminatingrelianceonnonportablenative

OSeventdemultiplexingAPIs,theACEReactorframework

providesapplicationswithauniformobject-orientedevent

detection,demulti-plexing,anddispatchingmechanism.

Eventhandlerobjectscanberegisteredwiththe

ACE_Reactortoprocessvarioustypesofevents.

Transparentextensibility.Theframeworkemployshook

methodsviainheritanceanddynamicbindingtodecouple

lower-leveleventmechanisms,suchasdetectingeventson

multipleI/Ohandles,expiringtimers,anddemultiplexing

anddispatchingmethodsoftheappropriateeventhandler

toprocesstheseevents,fromhigher-levelapplicationevent

processingpolicies,suchasconnectionestablishment

strategies,datamarshalinganddemarshaling,and

processingofclientrequests.ThisdesignallowstheACE

Reactorframeworktobeextendedtransparentlywithout

modifyingexistingapplicationcode.



Increasereuseandminimizeerrors.Developerswho

writeprogramsusingnativeOSeventdemultiplexing

operationsmustreimplement,debug,andoptimizethe

samelow-levelcodeforeachapplication.Incontrast,the

ACEReactorframework'seventdetection,demultiplexing,

anddispatchingmechanismsaregenericandcantherefore

bereusedbymanynetworkedapplications.Thisseparation

ofconcernsallowsdeveloperstofocusonhigh-level

application-definedeventhandlerpolicies,ratherthan

wrestlingrepeatedlywithlow-levelmechanisms.

Efficienteventdemultiplexing.TheACEReactor

frameworkperformsitseventdemultiplexingand

dispatchinglogicefficiently.Forinstance,the

ACE_Select_ReactorpresentedinSection4.2usesthe

ACE_Handle_Set_Iteratorwrapperfacadeclass

describedinChapter7ofC++NPv1.Thiswrapperfacade

usesanoptimizedimplementationoftheIteratorpattern

[GoF]toavoidexaminingfd_setbit-masksonebitata

time.Thisoptimizationisbasedonasophisticated

algorithmthatusestheC++exclusive-oroperatorto

reducerun-timecomplexityfromO(numberoftotalbits)to

O(numberofenabledbits),whichcanimprovetherun-time

performanceoflarge-scaleapplicationssubstantially.

Theremainderofthischaptermotivatesanddescribesthe

capabilitiesofeachclassintheACEReactorframework.We

illustratehowthisframeworkcanbeusedtoenhancethe

designofournetworkedloggingserver.Ifyouaren'tfamiliar

withtheReactorpatternfromPOSA2,werecommendthatyou

readaboutitfirstbeforedelvingintothedetailedexamplesin

thischapter.Chapter4thendescribesthedesignanduseofthe

mostcommonimplementationsoftheACE_Reactorinterface

presentedhere.Thatchapteralsodescribesthevarious

concurrencymodelssupportedbytheseACE_Reactor

implementations.



3.2TheACE_Time_ValueClass

Motivation

Differentoperatingsystemsprovidedifferentfunctionsanddata

toaccessandmanipulatethetimeanddate.Forexample,UNIX

platformsdefinethetimevalstructureasfollows:



structtimeval{

longsecs;

longusecs;

};

DifferentdateandtimerepresentationsareusedonotherOS

platforms,suchasPOSIX,Windows,andproprietaryreal-time

operatingsystems.Timevaluesareusedinanumberof

situations,includingtimeoutspecifiers.AsdescribedinSidebar

6(page45),ACEspecifiestimeoutsinabsolutetimeforsome

situations,suchastheconcurrencyandsynchronization

wrapperfacadesinC++NPv1,andinrelativetimeforother

situations,suchastheACE_ReactorI/Otimeoutsandtimer

settings.Thewiderangeofusesanddifferentrepresentations

acrossplatformsmakesaddressingtheseportabilitydifferences

ineachapplicationunnecessarilytediousandcostly,whichis

whytheACEReactorframeworkprovidestheACE_Time_Value

class.



ClassCapabilities

ACE_Time_ValueappliestheWrapperFacadepattern[POSA2]

andC++operatoroverloadingtosimplifytheuseofportable

timeanddurationrelatedoperations.Thisclassprovidesthe

followingcapabilities:



Itprovidesastandardizedrepresentationoftimethat's

portableacrossOSplatforms.

Itcanconvertbetweendifferentplatformtime

representations,suchastimespec_tandtimevalon

UNIX,andFILETIMEandtimevalonWindows.

Itusesoperatoroverloadingtosimplifytime-based

comparisonsbypermittingstandardC++syntaxfortimebasedarithmeticandrelationalexpressions.

Itsconstructorsandmethodsnormalizetimequantitiesby

convertingthefieldsinatimevalstructureintoa

canonicalformatthatensuresaccuratecomparisons

betweenACE_Time_Valueinstances.

Itcanrepresenteitheraduration,suchas5secondsand

310,000microseconds,oranabsolutedateandtime,such

as2001-09-11-08.46.00.Notethatsomemethods,suchas

operator*=(),aremeaninglesswithabsolutetimes.

TheinterfaceforACE_Time_ValueisshowninFigure3.2

(page44).Asyoureadthisbook,keepinmindthepointsnoted

inSidebar7(page46)regardingUMLdiagramsandC++code.

ThekeymethodsofACE_Time_Valueareoutlinedinthe

followingtable:



Method



Description



ACE_Time_Value() Overloadedconstructorsandmethodsthatconvertfromvarious

timeformats,suchastimeval,FILETIME,timespec_t,or

set()

long,toanormalizedACE_Time_Value.

sec()



Anaccessorthatreturnsthesecondsportionofan

ACE_Time_Value.



usec()



Anaccessorthatreturnsthemicrosecondsportionofan

ACE_Time_Value.



msec()



Convertsthesec()/usec()ACE_Time_Valueformatinto

millisecondformat.



operator+=()



Arithmeticmethodsthatadd,subtract,andmultiplyan

ACE_Time_Value.



operator-=()

operator*=()



Inadditiontothemethodsshownabove,thefollowingbinary

operatorsarefriendsoftheACE_Time_Valueclassthatdefine

arithmeticandrelationaloperations:

Method



Description



operator+() ArithmeticmethodsthataddandsubtracttwoACE_Time_Values.

operator-()

operator==

()



MethodsthatcomparetwoACE_Time_Valuesforequalityand

inequality.



operator!=

()

operator<() MethodsthatdeterminerelationshipsbetweentwoACE_Time_Values.

operator>()

operator<=

()

operator>=

()



AllACE_Time_Valueconstructorsandmethodsnormalizethe

timevaluestheyoperateon.Normalizationreduces

microsecondquantitiesequivalenttoonesecondormoreby

transferringthesecondsvaluetothesecsmember,leavingthe

remainingmicrosecondsvalueinusecs.Forexample,

normalizingthequantityACE_Time_Value(1,1000000)will

compareequaltothenormalizedACE_Time_Value(2)

quantity.Incontrast,abitwisecomparisonofnon-normalized

objectswon'tdetecttheirequivalence.

Figure3.2TheACE_Time_ValueClass



ACE_Time_Value

+zero:ACE_Time_Value

+max_time:ACE_Time_Value

-tv_:timeval

+ACE_Time_Value(sec:long,usec:long=0)

+ACE_Time_Value(t:conststructtimeval&)

+ACE_Time_Value(t:consttimespec_t&)

+ACE_Time_Value(t:constFILETIME&)

+set(sec:long,usec:long)

+set(t:conststructtimeval&)

+set(t:consttimespec_t&)

+set(t:constFILETIME&)

+sec():long

+usec():long

+msec():long

+operator+=(tv:constACE_Time_Value&):ACE_Time_V

+operator-=(tv:constACE_Time_Value&):ACE_Time_V

+operator*=(d:double):ACE_Time_Value&

Sidebar6describesthedifferencesintheinterpretationof

ACE_Time_Valuewhenusedtorepresenttimeoutvaluesfor



variousclassesinACE.



Example

ThefollowingexamplecreatestwoACE_Time_Valueobjects

whosevaluescanbesetviacommand-linearguments.Itthen

performsrangecheckingtoensurethevaluesarereasonable.



1#include"ace/OS.h"

2

3constACE_Time_Valuemax_interval(60*60);//1ho

4

5intmain(intargc,char*argv[]){

6ACE_Time_Valueexpiration=ACE_OS::gettimeofday(

7ACE_Time_Valueinterval;

8

9ACE_Get_Optopt(argc,argv,e:i:));

10for(intc;(c=opt())!=-1;)

11switch(c){

12'e':expiration+=ACE_Time_Value(atoi(opt.opt

13break;

14'i':interval=ACE_Time_Value(atoi(opt.opt_ar

15break;

16}

17if(interval>max_interval)

18cout<<"intervalmustbelessthan"

19<
20elseif(expiration>(ACE_Time_Value::max_time-

21cout<<"expiration+intervalmustbelessthan

22<
23return0;

24}



Sidebar6:AbsoluteversusRelativeACE_Time_ValueTimeouts

SomeACEclassesuserelativetimeouts,whereasothersuseabsolutetimeouts:



Relativetimesemantics

-ACEIPCwrapperfacadeI/Omethods(Chapter3inC++NPv1),

aswellashigherlevelframeworkclassesthatusethem,suchas

thoseintheACEAcceptor-Connectorframework(Chapter7)

-ACE_ReactorandACE_Proactoreventloopandtimer

schedulingmethods(Chapters3and8)

-ACE_Process,ACE_Process_Manager,and

ACE_Thread_Managerwait()methods(Chapters8and9in

C++NPv1)and

-TimeslicequantumforACE_Sched_Params(Chapter9in

C++NPv1).

Absolutetimesemantics

-ACEsynchronizerwrapperfacades,suchas

ACE_Condition_Thread_MutexandACE_Thread_Semaphore

(Chapter10inC++NPv1)

-ACEtimerqueueschedulingmethods(Chapter3)

-ACE_Taskmethods(Chapter6)and

-ACE_Message_Queuemethods(Chapter6),aswellasclasses

basedonorthatuseACE_Message_Queue,suchasthoseinthe

ACEStreamsframework(Chapter9)and

ACE_Activation_Queue,ACE_Future,andACE_Future_Set

[HJS].



Relativetimeoutsareoftenusedwheretheoperation

(suchasanACE_Thread_Manager::wait()

operation)maydelaybeforebeingabletoproceed,but

willbecalledonlyonce.Conversely,absolutetimeouts

areoftenusedwheretheoperation(suchasan



ACE_Condition_Thread_Mutex::wait()

operation)maybecalledmultipletimesviaaloop.Use

ofabsolutetimeavoidstheneedtorecomputethe



timeoutvalueforeachloopiteration[KSS96].



Lines3–7InitializetheACE_Time_Valueobjects.Bydefault,

anACE_Time_Valueobjectisinitializedtozero.

Lines9–16Parsethecommand-lineargumentsusingthe

ACE_Get_OptclassdescribedinSidebar8(page47).

Lines17–22Performrangecheckingtoensurethevaluesare

reasonable.



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

Chapter 3. The ACE Reactor Framework

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

×