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

Chapter 6. The ACE Task Framework

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

6.1Overview

TheACETaskframeworkprovidespowerfulandextensible

object-orientedconcurrencycapabilitiesthatcanspawnthreads

inthecontextofanobject,aswellastransferandqueue

messagesbetweenobjectsexecutinginseparatethreads.This

frameworkcanbeappliedtoimplementkeyconcurrency

patterns[POSA2],suchas:

TheActiveObjectpattern,whichdecouplesthethreadthat

invokesamethodfromthethreadthatexecutesthe

method.Thispatternenhancesconcurrencyandsimplifies

synchronizedaccesstoobjectsexecutinginthecontextof

oneormorethreads.

TheHalf-Sync/Half-Asyncpattern,whichdecouples

asynchronousandsynchronousprocessinginconcurrent

systemstosimplifyprogrammingwithoutundulyreducing

performance.Thispatternintroducesthreelayers:onefor

asynchronous(orreactive)processing,oneforsynchronous

serviceprocessing,andaqueueinglayerthatmediates

communicationbetweentheasynchronous/reactiveand

synchronouslayers.

Thischaptershowshowthesepatterns,andtheACETask

frameworkthatreifiesthem,canbeappliedtodevelop

concurrentobject-orientedapplicationsatahigherlevelof

abstractionthanexistingCoperatingsystemAPIsandC++

wrapperfacades.TheACETaskframeworkconsistsofthe

followingclassesthatnetworkedapplicationscanusetospawn

andmanagethreadsandpassmessagesbetweenoneormore

threadswithinaprocess:

ACEClass



Description



ACE_Message_Block ImplementstheCompositepattern[GoF]toenableefficient

manipulationoffixed-andvariable-sizedmessages



ACE_Message_Queue Providesanintraprocessmessagequeuethatenables

applicationstopassandbuffermessagesbetweenthreadsina

process



ACE_Thread_Manager Allowsapplicationstoportablycreateandmanagethelifetime,

synchronization,andpropertiesofoneormorethreads



ACE_Task



Allowsapplicationstocreatepassiveoractiveobjectsthat

decoupledifferentunitsofprocessing;usemessagesto

communicaterequests,responses,data,andcontrol

information;andcanqueueandprocessmessagessequentially

orconcurrently



Themostimportantrelationshipsbetweentheclassesinthe

ACETaskframeworkareshowninFigure6.1.Thisframework

providesthefollowingbenefits:

Figure6.1.TheACETaskFrameworkClasses



Improvestheconsistencyofprogrammingstyleby

enablingdeveloperstouseC++andobject-oriented

techniquesthroughouttheirconcurrentnetworked

applications.Forexample,theACE_Taskclassprovidesan

object-orientedprogrammingabstractionthatassociates

OS-levelthreadswithC++objects.



Managesagroupofthreadsasacohesivecollection.

Multithreadednetworkedapplicationsoftenrequiremultiple

threadstostartandendasagroup.TheACE_Taskclass

thereforeprovidesathreadgroupcapabilitythatallows

otherthreadstowaitforanentiregroupofthreadstoexit

beforecontinuingtheirprocessing.

Decouplesproducerandconsumerthreadsthatrun

concurrentlyandcollaboratebypassingmessagesviaa

synchronizedmessagequeue.

Integratesconcurrentprocessing,suchastheHalfSync/Half-Asyncpattern'ssynchronouslayer,withtheACE

ReactorframeworkdiscussedinChapter3ortheACE

ProactorframeworkdiscussedinChapter8.

Facilitatesdynamicconfigurationoftasksvia

integrationwiththeACEServiceConfiguratorframework

discussedinChapter5.Developersthereforeneednot

commitprematurelytoconcurrencydecisionsatdesign

timeorevenatruntime.Taskscaninsteadbedesignedto

runaccordingtoconfigurationsthatmaychangeas

deploymentsiteresourcesanddynamicconditionsdictate.

TheACE_Message_BlockandACE_Thread_Managerclasses

weredescribedinChapters4and9ofC++NPv1,respectively.

Thischapterthereforefocuseslargelyondescribingthe

capabilitiesprovidedbytheACE_Message_Queueand

ACE_Taskclasses.However,weillustratehowalltheclassesin

theACETaskframeworkcanbeusedtoenhancethe

concurrencyofourclientandserverloggingdaemons.Ifyou

aren'tfamiliarwiththeActiveObjectandHalf-Sync/Half-Async

patternsfromPOSA2werecommendthatyoureadaboutthem

firstbeforedelvingintothedetailedexamplesinthischapter.



6.2TheACE_Message_QueueClass

Motivation

AsdiscussedinSection2.1.4onpage27,networked

applicationswhoseservicesarelayered/modularareoften

composedofasetofcollaboratingtaskswithinaprocess.To

simplifyinterfacesanddesign,minimizemaintenancecosts,and

maximizereuse,thesetasksshouldhavethefollowing

properties:

Lowintertaskcoupling,thatis,separatetaskobjects

shouldhaveminimaldependenciesoneachother'sdataand

methods.

Highintrataskcohesion,thatis,themethodsanddatain

ataskshouldfocusonarelatedsetoffunctionality.

Toachievetheseproperties,tasksoftencommunicateby

passingmessagesviaagenericmethod,suchaspush()or

put(),ratherthancallingspecificstaticallytypedmethods

directly.Messagescanrepresentworkrequests,workresults,or

othertypesofdatatoprocess.Theycanalsorepresentcontrol

requeststhatdirecttaskstoaltertheirprocessing,forexample,

toshutdownorreconfigurethemselves.

Whenproducerandconsumertasksarecollocatedinthesame

process,tasksoftenexchangemessagesviaanintraprocess

messagequeue.Inthisdesign,producertask(s)insert

messagesintoasynchronizedmessagequeueservicedby

consumertask(s)thatremoveandprocessthemessages.Ifthe

queueisfull,producerscaneitherblockorwaitabounded

amountoftimetoinserttheirmessages.Likewise,ifthequeue

isempty,consumerscaneitherblockorwaitaboundedamount



oftimetoremovemessages.

Althoughsomeoperatingsystemssupplyintraprocessmessage

queuesnatively,thiscapabilityisn'tavailableonallplatforms.

Moreover,whenitisoffered,it'softeneitherhighlyplatform

specific,suchasVxWorksmessagequeues,and/orinefficient,

tedious,anderrorpronetouse,suchasSystemVIPCmessage

queues[Ste99].Examplesofhowtocreatewrapperfacade

classestohandletheseproblemsappearinC++NPv1.Wrapper

facadescouldencapsulatethespectrumofavailable

intraprocessmessagequeuemechanismsbehindacommon

interface,emulatingmissingcapabilitieswhereneeded.ACE

takesadifferentapproach,however,forthefollowingreasons:

Toavoidunnecessarycomplexity.Nativemessage

queueingmechanisms,wheretheyexist,canbehardto

programcorrectlysincetheyuselow-levelCAPIs.Theycan

alsoimposeconstraintsonsystemadministrationthat

reflectpoorlyonaproduct'soperationalprocedures,which

canincreaseproductsupportcosts.Forexample,SystemV

IPCmessagequeuescanpersistafteraprogramfinishes

executionifnotcleanedupproperly.Theseremnantsmay

preventanapplicationfromrestarting,orcontributeto

resourceleaksandoftenrequireasystemadministrator's

interventiontorepairthesystemmanually.Likewise,

SystemVIPCmessagequeuesofferinterprocessqueueing

thatincursmoreoverheadthantheintraprocessqueueing

that'sthetargetusecaseformanynetworkedapplications.

Toavoidamatrixofincreasingcomplexity.Eachnative

messagequeueingmechanismhasitsownmessageformat.

Properlyencapsulatingmessagequeueswithwrapper

facadesthereforerequiresacorrespondingencapsulationof

messages.Reconcilingtwowrappers'desiredfeaturesets

withthematrixofmessagequeuesandtypescomplicates

thedesignanddevelopmenteffortforthewrappersmany



timesover.ThisproblemwouldonlygetworseasACEis

portedtonewplatforms.

ACEalreadyhasapowerfulmessageclass.

ACE_Message_Blockisaconvenient,efficient,and

powerfulmessageclassdescribedinChapter4of

C++NPv1.Itoffersmorecapabilitythanmanyplatformspecificmessageformats,andalsoworksportablyacrossall

ACEplatforms.

Duetothesefactors,ACEdefinestheACE_Message_Queue

class,whichisaportableandefficientintraprocessmessage

queueingmechanismthatleveragestheadvancedcapabilities

ofACE_Message_Block.



ClassCapabilities

ACE_Message_Queueisaportable,lightweightintraprocess

messagequeueingmechanismthatprovidesthefollowing

capabilities:

Itallowsmessages(whichareinstancesof

ACE_Message_Block)tobeenqueuedatthefrontofthe

queue,therearofthequeue,orinpriorityorderbasedon

themessage'spriority.Messagescanbedequeuedfromthe

frontorbackofthequeue.

ItusesACE_Message_Blocktoprovideanefficient

messagebufferingmechanismthatminimizesdynamic

memoryallocationanddatacopying.

Itcanbeinstantiatedforeithermultithreadedorsinglethreadedconfigurations,allowingprogrammerstotradeoff

strictsynchronizationforloweroverheadwhenconcurrent

accesstoaqueueisn'trequired.



Inmultithreadedconfigurations,itsupportsconfigurable

flowcontrol,whichpreventsfastmessageproducer

thread(s)fromswampingtheprocessingandmemory

resourcesofslowermessageconsumerthread(s).

Itallowstimeoutstobespecifiedonbothenqueueand

dequeueoperationstoavoidindefiniteblocking.

ItcanbeintegratedwiththeACEReactorframework's

eventhandlingmechanism.

Itprovidesallocatorsthatcanbestrategizedsothe

memoryusedbymessagescanbeobtainedfromvarious

sources,suchassharedmemory,heapmemory,static

memory,orthread-specificmemory.

Figure6.2(page160)showstheinterfacefor

ACE_Message_Queue.Sincethisclasshasawiderangeof

features,wedivideitsdescriptionintothefourcategories

below.

Figure6.2.TheACE_Message_QueueClass



1.Initializationandflowcontrolmethods.Thefollowing

methodscanbeusedtoinitializeandmanageflowcontrolinan

ACE_Message_Queue:



Method



Description



ACE_Message_Queue()

open()



Initializethequeue,optionallyspecifyingwatermarksand

anotificationstrategy(seeSidebar38onpage163).



high_water_mark()



Set/getthehighandlowwatermarksthatdetermine

whenflowcontrolstartsandstops.



low_water_mark()

notification_strategy() Set/getthenotificationstrategy.



AnACE_Message_Queuecontainsapairofwatermarksthat

implementflowcontroltopreventafastsenderfrom

overrunningthebufferingandcomputingresourcesofaslower

receiver.Toreflectthetotalresourceusageofmessagesinthe

queue,thewatermarksaremeasuredinbytes.Each

ACE_Message_Queuemaintainsacountofthepayloadbytesin

eachqueuedACE_Message_Blocktokeeptrackofthenumber

ofbytesinthequeue.Anewmessagecanbeenqueuedifthe

totalnumberofbytesinthequeuebeforequeueingthenew

messageislessthanorequaltothehighwatermark.

Otherwise,ACE_Message_Queueflowcontrolworksasfollows:

Ifthequeueis"synchronized,"thecallingthreadwillblock

untilthetotalnumberofbytesinthequeuefallsbelowthe

lowwatermarkoruntilatimeoutoccurs.

Ifthequeueis"unsynchronized,"thecallwillreturn-1with

errnosettoEWOULDBLOCK.

TheACE_MT_SYNCHorACE_NULL_SYNCHtraitsclasses(page

163)canbeusedtodesignatewhetheraqueueissynchronized

ornot,respectively.AsACE_Message_Blockobjectsare

removedfromamessagequeue,thecountofqueuedbytesis

decrementedaccordingly.Thelowwatermarkindicatesthe

numberofqueuedbytesatwhichapreviouslyflow-controlled

ACE_Message_Queuenolongerconsidersitselffull.

Thedefaulthighandlowwatermarksareboth16K.Thedefault

watermarkvaluescauseanACE_Message_Queuetoflow

controlwhenmorethan16Karequeuedandtoceaseflow

controlwhenthenumberofqueuedbytesdropsbelow16K.

Thesedefaultsareappropriateforapplicationsinwhichthe

averageACE_Message_Blocksizeisconsiderablylessthan

1K.

Dependingonloadanddesignconstraints,applicationsmay



requiredifferentsettingsforeitherorbothofthewatermarks.

Thedefaultwatermarkvaluescanberesetinthe

ACE_Message_Queue'sconstructororopen()method,aswell

asbyitshigh_water_mark()andlow_water_mark()

mutatormethods.Oneapproachistospecifywatermarksusing

theACEServiceConfiguratorframeworkdescribedinChapter5,

withdefaultsdeterminedfromapplicationbenchmarks

measuredduringdevelopmentandtesting.TheExample

portionsofSections6.3and7.4illustratehowtosetandusea

messagequeue'shighwatermarktoexertflowcontrolwithin

multithreadednetworkedapplications.

2.Enqueue/dequeuemethodsandmessagebuffering.

Thefollowingmethodsperformthebulkoftheworkinan

ACE_Message_Queue:



Method



is_empty()

is_full()



Description



Theis_empty()methodreturnstruewhenthequeuecontainsno

messageblocks.Theis_full()methodreturnstruewhenthe

numberofbytesinthequeueisgreaterthanthehighwatermark.



enqueue_tail() Insertamessageatthebackofthequeue.

enqueue_head() Insertamessageatthefrontofthequeue.

enqueue_prio() Insertamessageaccordingtoitspriority.

dequeue_head() Removeandreturnthemessageatthefrontofthequeue.

dequeue_tail() Removeandreturnthemessageatthebackofthequeue.



ThedesignoftheACE_Message_Queueclassisbasedonthe

messagebufferingandqueueingfacilitiesinSystemVSTREAMS

[Rag93].Messagespassedtoamessagequeueareinstancesof



ACE_Message_Blockandcanbeclassifiedaseithersimpleor

compositemessages.Simplemessagescontainasingle

ACE_Message_Block.Compositemessagescontainmultiple

ACE_Message_Blockobjectsthatarelinkedtogetherin

accordancewiththeCompositepattern[GoF],whichprovidesa

structureforbuildingrecursiveaggregations.Acomposite

messageoftencontainsthefollowingmessagetypes:

Acontrolmessagethatcontainsbookkeepinginformation,

suchasdestinationaddressesandlengthfields,followedby

Oneormoredatamessagesthatcontaintheactual

contentsofacompositemessage

Messagesinaqueuearelinkedbidirectionallyviaapairof

pointersthatcanbeobtainedusingtheirnext()andprev()

accessormethods.Thisdesignoptimizesenqueueingand

dequeueingattheheadandtailofaqueue.Priority-based

queueingwiththeACE_Message_Queue::enqueue_prio()

methodusestheACE_Message_Block::msg_priority()

accessormethodtoenqueueamessageblockaheadofall

lower-prioritymessageblocksalreadyinthequeue.Message

blocksatthesamepriorityareenqueuedinfirst-in,first-out

(FIFO)order.

Eachmessageblockinacompositemessageischained

togetherunidirectionallyviaacontinuationpointer,whichcan

beobtainedviathecont()accessormethod.Figure6.3(page

162)illustrateshowthreemessagescanbelinkedtogetherto

formanACE_Message_Queue.Theheadandtailmessagesin

thequeuearesimplemessages,whereasthemiddleoneisa

compositemessagewithonemessageblockchainedviaits

continuationpointer.

Figure6.3.TheStructureofanACE_Message_Queue



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

Chapter 6. The ACE Task Framework

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

×