0% found this document useful (0 votes)
447 views5 pages

NI Actor Framework Whitepaper

Detailed description of the NI Actor Framework.

Uploaded by

Balázs Nagy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
447 views5 pages

NI Actor Framework Whitepaper

Detailed description of the NI Actor Framework.

Uploaded by

Balázs Nagy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

2016.03.22.

ActorFrameworkWhitepaper

ActorFrameworkWhitepaper
TheActorFrameworkisasoftwarelibrarythatsupportsthewritingofapplicationsinwhichmultipleVIsrunindependentlywhilecommunicatingwith
eachother.Intheseapplications,eachVIrepresentssomeactorcarryingoutanindependenttaskinthesystem.Theactormaintainsitsinternalstate
andsendsmessagesouttotheotheractors.ManytechniquesexistforcreatingsuchapplicationsinLabVIEW.TheActorFrameworkfocusesonbeing
easytolearn(relativetootherpossiblymorepowerfultools)whilemitigatingriskofdeadlocks/raceconditionsandmaximizingcodereuse.
NationalInstrumentscreatedTheActorFrameworktofillaholeinthestandardarchitecturesusedbyLabVIEWprogrammers.TheActorFramework
buildsonthewellknownqueuedrivenstatemachine1 (QDSM)model,whichisshowninthefollowingfigure.

TheQDSMisoneoftwopatternsusedinthemajorityofLabVIEWapplications(theotherbeingtheProducer/Consumermodel).IndividualQDSMsare
wellencapsulatedsoftwaremodulesthatcancombinetocreatelargesystemswithrichbehavior.ManyLVwrittenapplicationsdothissuccessfullybut
oftencontaintwocommonpitfalls.First,althoughtheQDSMisgoodfordefiningamodule,themodulesthemselvesoftenhavelimitedreusepotential.In
manyapplications,astatemachinewrittentorepresentonesubsystemorpieceofhardwarewouldbeduplicatedinitsentiretytosupportanother
similarsubsystemorpieceofhardware.Second,everyapplicationframeworkhadatleastonepotentialtimingrelatedbuginitscommunicationscheme.
Whenindividualprogrammerscreateamessagingscheme,theyoftenintroducesubtleerrorsinvolvingresourcecontention,excessivecouplingbetween
modules,missedmessagesordeadlocks.
Byapplyingsomecommonobjectorientedtechniquesanddesignpatternstotheoriginalqueuedrivenstatemachine,NationalInstrumentscreateda
frameworkthatprovides:
AllofthebenefitsofQDSMdesign
Significantlyincreasedflexibility
Morereusepotential
Reducedcouplingbetweenmodules

BasicActorFramework
TheActorFrameworkisasetofclassesthatprovidecommonstateandmessagehandlingfunctions.
Themodelprovidesthefollowingtwoparentclassesfromwhichyoucreatechildclasses:
ActorStatedatainamodule.
MessageMessagespassedbetweenactorstotriggerstatechanges.
TheActorFrameworkincludestwospecificMessagechildclassescalledStopMsgandLastAck.Thesechildclassesareparticularmessagesused
whenshuttingdownactors.AdditionalMessagechildclassesaredistributedwiththeframework,butarenotincludedintheframeworklibraryitself
sincetheynotrequiredinallapplications.Theseadditionalmessageclassessupportoptionalusecases.
Underthehood,theframeworkmakesextensiveuseofLabVIEW'squeuefunctions.ThepublicAPI,however,hidetherawqueuesusingtheMessage
Enqueuerclass.ThisclassisawrapperaroundLabVIEW'squeuereferencesthatprovidesonlytheabilitytoenqueue.Thismeansthereferencemay
besharedwithotherprocesseswithoutworryingthattheotherprocessesaremessingwiththeinvariantsonwhichtheActorFrameworkispredicated.
Theotherprocessescannotdestroythequeueprematurely,theycannotflushthequeue,etc.MessageEnqueuerprovidesfourlevelsofpriority
enqueuebehavior,whilemaintainingthesamehighperformanceforwhichtheLabVIEWqueuesareknown.Bylimitingwhatcanbedonetothequeues
invariouspartsofthecode,theframeworkisabletomakeguaranteesabouttimingandmessagedeliverythatotherwisecouldnotbeproven.
TherearetwootherwrapperclassesintheAPI,MessageQueueandMessageDequeuer.Theseareusedonlyinadvancedusecasesandarenot
discussedfurtherinthisdocument.

Actors
IntheActorFramework,anactorisaLabVIEWobjectthatrepresentsthestateofanindependentlyrunningVI.Becausetheactorobjectisshielded
insidetherunningVIandalloutsideaccessisdonebysendingmessagestotheVI,theterm"actor"isalsousedfortheVIitself.Theflexibleusageof
thetermbecomesnaturalonceyouunderstandhowtightlypairedtheactorobjectbecomeswiththeVIhostingit.AllactorclassesinheritfromActor.
Anactorobjectisanormalbyvalue,dataflowobjectwithaccessorsandmethods.Youcanmakeanyexistingclassintoanactorsimplybysettingitto
inheritfromActor.
ActorprovidesexactlyonepublicmethodcalledLaunchRootActor.vi,showninthefollowingfigure.

ThismethodusesVIServertolaunchanindependentreentrantcloneoftheprotectedmethod,ActorCore.vi,whichdefinestheQDSM.LaunchActor.vi
hasonerequiredinput:theinitialactorobject.TheVIreturnsanewenqueuerreferenceobjectasoutput.Youwillusetheoutputenqueuertosend
messagesintotheActorCore.viwhileitisrunning.NotethatLaunchActor.vidoesnotreturntheActorobjectitispassedfromLaunchActor.vito
ActorCore.viandisnolongeravailabletothecaller.Allfurtherinteractionwiththeobjectisdonebypassingmessagesintothemessagequeuethrough
theenqueuer.
ActoralsohasaprotectedscopemethodcalledLaunchNestedActor.vi.

file:///D:/%23%23Trainings/LV/OOP_other/OOP_ARCHITECTURES/%23AF/my_AF_test_LV_2014/documentation/Actor%20Framework%20Whitepaper.h 1/5

2016.03.22.

ActorFrameworkWhitepaper

Ingeneral,onlyoneactorinyourapplicationshouldbelaunchedusingLaunchRootActor.vi.Therootactorformsthetopofatree.Otheractorsare
launchedassubprocessesusingLaunchNestedActor.vi.Asyoucansee,launchinganestedactorisverymuchlikelaunchingtherootactor,butwith
theadditionofacalleractorinput.TherelationshipbetweenacalleractorandanestedactoriscentraltothedesignoftheActorFramework.Most
actorshaveacaller.Unlessyoudosomethingspecialinyourcode,theonlypartsofyourcodethatcansendmessagestoanactoraretheactoritself,
itscalleroritsowndirectnestedactors.Thismeansthatactorsformatree,notagraph,andmessagesarepassedthroughthetreebypassingupto
callersandthen,ifthecallerdecides,downtoothernestedactors.Wewilldiscussstheactortreeingreaterdetail.
Bydefault,stoppinganactorwillstopallofitsnestedactors.
BecauseLaunchRootActor.viandLaunchNestedActor.viareessentiallythesamefunctionusedintwodifferentcontexts,itisfrequentlyusefultotalk
aboutthemasone.ThisdocumentwilluseLaunch<X>Actor.viwhentalkingaboutbothfunctions.
Note:EarlierversionsoftheActorFrameworkhadasingleLaunchActor.vithatlaunchedbothrootandnestedactors.ThisVIhasbeendeprecatedin
responsetocommunityfeedbacktomaketheframeworkeasiertouse.Ifyouseeitusedincode,youshouldreplaceitwithoneofthenewerVIs.
ActorCore.viisaprotectedscope,dynamicdispatchVI.HereistheActorclass'implementation:

YoushouldrecognizeActorCore.viasaqueuedrivenstatemachine.Aseachmessagearrives,themessageinvokesmethodsontheactor(see
"Messages,"below).Anerrorwillstopthestatemachine,althoughspecialconsiderationisgiventoerrorcode43,CancelError,whichdoesstopthe
machinebutdoesnotpropagateuptocallers.
AchildclasscanoverrideActorCore.vi,thoughtheoverrideVImustinvoketheCallParentnode.BecausetheCallParentnoderunsthestatemachine,it
shouldbeinparallel,notserial,withotheroperationsyouaddintheoverrideVI.TheoverrideVIcanincludeauserinterface,callstolaunchnested
actors,oradditionalcontrollogicforthestatemachine.Youwillfindmoredetailsabouttheseoverrideslaterinthisdocument.

UserInterfacesforActors
TheActorFrameworkdoesnotprovidethemethodVIsofyouractorwithanydirectlyaccesstocontrols,indicators,orparallelloopsthatmightbepart
ofitsoverrideofActorCore.vi.Youmustdefinethataccesswithinyouractor.
Herearetwoeasywaystodefinethataccesswithinyouractor:
1.Includeareferenceinyouractor'sprivatedatatoeitheryourActorCore.viortoitsfrontpanelobjects.Bundlethesereferencesintothe
actorbeforeinvokingtheCallParentnode.Youractorcanthenaccessthesereferencesfromwithinanyofitsmethods.Thismethodallows
yourmethodstocontroltheuserinterfaceoftheActorCore.vi,althoughitmaynotbethemostefficientapproach.Thisapproachworks
wellforinterfacesthatareonlydisplayinginformationandnotreactingtousers'actions.
2.Createasetofusereventstomanageyourfrontpanelupdates.CreatetheseeventsinyourActorCore.viandbundlethemintotheactor
objectpriortoinvokingtheCallParentnode.ThencreatealoopinyourActorCore.vithatrunsinparalleltotheCallParentnodewhichis
dynamicallyregisteredfortheevents.Whentheactorreceivesamessage,thehandlingfunctionforthatmessagecangeneratethe
appropriateeventandpassalonganyrelevantdata.Alternatively,youmaychoosetousequeues,notifiers,orothermechanismsto
communicatewithyourparallelloopratherthanevents.Regardlessofwhichmechanismyouprefer,NationalInstrumentsrecommendsthat
youselectonlyonedatatransfermechanismwithinanygivenactor,andkeepthetotalnumberofsuchmechanismstoaminimumwithin
theapplicationasawhole.BesuretoprovideamechanismtostopyourparallelloopandtriggerthatmechanismbyoverridingStopCore.vi
inyouractorchildclass.

Messages
Usemessageobjectstomodifythestateofanactorobject.Messageobjectstaketheplaceofindividualcasesinatraditionalqueuedrivenstate
machine.MessageobjectsinheritfromMessage,andmustoverridetheDo.vimethod.ChildMessageclassesusuallyincludesomeattributedataanda
Send<message>.vimethod.Dependingontheapplication,theremaybeadditionalmethodsforreadingorwritingthemessagedata.
ThequeuespassedtoandreturnedbyLaunchActor.vitakemessagesastheirdatatype.AVIthatneedstointeractwithanactormusthaveaccessto
theactor'smessageenqueuer.TheVIcreatesamessageofthedesiredtypeandenqueuesittotheactor'squeue.TypicallytheVIaccomplishesthisby
invokingtherelevantSend<message>.vi.Send<message>.vicombinescreatingthemessage,writingitsdata,andpostingittothequeueinasingle
call.Youcanperformthesetasksseparatelyifdesired.
Youmustprovideamessageforeverymethodofyouractorthatyouwanttoaccessremotely.Amessagetypicallyrepresentsacalltoonemethodofthe
class,andthemessageclass'privatedataistheinputparametersneededtoinvokethatmethod.Whenyouractorreceivesamessage,itinvokesthat
message'sDo.vimethod.Do.viinturninvokestheappropriateoperationontheactor.Mostapplicationshaveaonetoonecorrespondencebetweena
messageclassandanactor'smethod,buttherearerarecaseswhereasinglemessagerepresentsmultipleoperationsontheactor.Creatingthese
messageclassesmaysoundtedious,buttheActorFrameworkincludesascriptingtool,discussedlater,toeliminatethebusywork.
Youcanusemessagesyoucreateforaspecificactorclasswithanychildofthatactor.Forexample,considerafancontrollerthatexposesapublic
methodToggleOn.viforturningthefanonoroff.Theprogrammercreatesacorrespondingmessageclass,ToggleOnMsg,thatthecontroller'scaller
canusetoinvokethatmethod.ThefollowingfigureshowstheDo.viforToggleOnMsg.

file:///D:/%23%23Trainings/LV/OOP_other/OOP_ARCHITECTURES/%23AF/my_AF_test_LV_2014/documentation/Actor%20Framework%20Whitepaper.h 2/5

2016.03.22.

ActorFrameworkWhitepaper

Whataboutoutputsfromthemethods?ThemoreyouworkwiththeActorFramework,themoreyouwillfindyourselfcreatingmanymethodsthathave
nooutputsotherthantheactorobjectanderrorout.Thisisbecausethemessagepassingenvironmentencouragesmethodsthataremoreabout
reactingtoinformationsentbyotherobjectsandlessaboutrequestinginformationfromotherobjects.Often,insteadofhavingoutputparameters,the
methoditselfwillsendamessagetoitscallerorotheractorsaspartofitsexecution.

Havingsaidthat,needingtopassdatabacktoacallerafteramessageisfinishedbeinghandledisnotuncommon.Iftheactormethoddoeshave
outputs,youcanaddanothermethodtotheactortowraptheonewithoutputs,andwithinthewrapperVI,useReadCallerEnqueuer.vi.Thisassumes,
ofcourse,thatthemessagecamefromthecalleroriginally.Iftheoriginalsenderwasnotthecaller,thesendermayprovideaninstanceofSelf
AddressedMessageintheoriginalrequesttouseforthereply.Ineithercase,thecaller/senderhearsthisreplyasynchronously.Inotherwords,the
caller/senderisnotwaitingforareplybutisinsteadproceedingwithitsownwork.Theuseofasynchronousmessagingbetweenactorsisstrongly
preferredwithintheActorFramework.RefertotheSynchronousReplyMessagessectionbelowforinformationaboutactorinteractionsrequiring
synchronousreplies.MoreinformationaboutreplyingtomessagesisdiscussedintheMessagesfromCalleetoCallersection,below.

MessageTypes
TheActorFrameworkshipswithsixmessagetypes.
1.MessageTheparentmessageclass.Onlymessagesthatarechildrenofthisclassarevalidmessageswithintheframework.Anactorthat
receivesaninstanceofMessagewilltakenoaction,sothiscanbeusedasanullmessage.DescendantsofMessagemustoverrideDo.vi.
2.StopMsgTellsanactortoshutdown.Theactorwillstophandlingfurthermessagesandwillperformanycleanupworkdefinedinits
StopCore.vi.IfyouractorlaunchesanynestedactorsinitsActorCore.vioverride,thoseactorswillbeautomaticallystoppedifyouwired
TruetotheAutostop?inputofLaunchNestedActor.vi.Ifyouchosetotakemanualcontrolofyournestedactors,youractorwillprobably
wanttoalsooverrideStopCore.viandpassthestopmessagealongtothosenestedactors.StopMsghastwodifferentSendmethodsone
sendsthemessageatNormalpriority.TheothersendsthemessageatEmergencypriority,whichisevenhigherthantheHighpriority.
ThisisoneofonlytwomessagesintheframeworkthatcaneverbesentatEmergencypriority.ReviewtheContextHelpfortheSend
EmergencyStop.viforfurtherinformation.
3.LastAckGivesacallerthefinalstateofanactorthathasshutdown.TheLastAck.lvclasscarriesthecallee'sfinalerror(ifany)andthe
finalvalueoftheactorforusebythecaller.Younevergettosendthismessage.Itissentforyoubytheframework,alwaysatEmergency
priority.
4.BatchMsgCollectsseveralothermessageobjectstogetherintoonesotheyaresenttoanactorinasingleatomicburst.SendBatch.vi
takesanarrayofmessageobjectsandbundlesthemintoasinglemessage.TheDo.viofBatchMsgiteratesthroughthearrayinaFor
Loop.Thisguaranteesthatnoothermessagescanbeenqueuedinbetweenthebatchedmessages,whichcanbeaconcernifyouenqueue
eachmessageindividually.
5.SelfAddressedMsgWrapsaregularmessageandthemessageenqueueroftheactorthatreceivesthemessage.AddressMessage.vi
createsthewrappedmessageandrecordsthequeueforthemessagetobesentbackalong.SendSelfAddressedMsg.visendsthe
preconfiguredmessagetothespecifiedqueue,makingthismessagetypecompletelyselfcontained.Useittosendmessagesfromasource
thathasnoknowledgeabouttherecipient.
6.ReplyMsg.lvclassDefinessynchronousmessages.Refertothenextsection.

SynchronousReplyMessages
Whenamessagerequiresthatyourcallerwaitforasynchronousresponsetothemessage,youcancreateanewmessageclassthatinheritsfrom
ReplyMsg.AreplymessageissentusingSendMessageandWaitforResponse.vi.Itbundlesasingleusequeueintothemessageandthenwaitsfora
replyonthatqueue(withprovisionfortimingoutifdesired).UsuallyyournewmessageclasswillhaveitsownSend<message>.viwhichwrapsSend
MessageandWaitforResponse.vi.YournewmessageclasswilloverrideDoCore.viinsteadofDo.viandreturnamessageforthecaller.Figure4shows
anexampleofhowtheReplyMsgDo.vipassesthatmessagebacktothecaller.
DonotoverrideDo.vioftheReplyMsgclass.Instead,overridetheprotectedDoCore.vi.HaveDoCore.vicalltheappropriatemethodofyouractorand
whateverotherfunctionalityyourequire,thenreturnasuitablemessagetosendtothecaller.ThedefaultbehaviorreturnsaninstanceofMessage.You
donothavetooverrideDoCore.viiftheonlyfeedbackyourmessagerequiresisacknowledgementofreceipt.
UsingReplyMsgcreatesthepotentialfordeadlocksituations.Forexample,ifthecallersendsasynchronousmessagetothecalleeatthesametime
thatthecalleesendsasynchronousmessagebacktothecaller,theapplicationwilldeadlock.Tominimizetherisk,useReplyMsgsparingly.Iftwo
actorsareabletocommunicatewitheachother(aswhenoneisthecallerandtheotheristhecallee),ifoneofthemcansendreplymessages,avoid
havinganyreplymessagesontheother.Alsotakecaretoavoidcascadingreplymessages,wherethecaller'sreplycausesthecalleetosendareply
message,asthis"echochamber"effectcanleadtoinfinitemessagespawning.

file:///D:/%23%23Trainings/LV/OOP_other/OOP_ARCHITECTURES/%23AF/my_AF_test_LV_2014/documentation/Actor%20Framework%20Whitepaper.h 3/5

2016.03.22.

ActorFrameworkWhitepaper

MessagesfromCalleetoCaller
Whenacallerwantstosendamessagetothecallee,thecallerknowsthetypeoftheactorthatitlaunched,socallercaneasilychoosetherighttypeof
messagetosend.Butwhenanactorwantstosendamessagetoitscaller,theactordoesnotnecessarilyknowwhattypeofcallerithas,soitdoesnot
knowwhattypeofmessagetosend.Ideally,actorsshouldbeusablebymanydifferentcallers.Thatmaximizescodereuse.Butmakingtheactortruly
independentofthecallerrequiresmoreeffortthaniswarrantedforthesituation.Therearethreetechniquesfordefiningmessagesthatanactorsends
toitscaller
1.TheHighCouplingSolutionInthissolution,thecalleeactoriswrittenspecificallyforonetypeofcaller,andcanneverbeusedwith
anyothertypeofcaller.Inthiscase,thecalleeknowsdetailsaboutthecaller'sinterface,soitmaysimplycalltheSendMessageVIofthe
appropriatemessage.Themessagetypeisthushardcodedintotheactor.
2.TheLowCouplingSolutionThissolutionworksbestwhenyouhaveaknowninheritancehierarchyofcallers.Inthissolution,you
createamatchinghierarchyofcalleeactors.SosupposeyouhavecallersHardDrive,AirConditioner,andFireSuppression,eachof
whichneedstolaunchaFanactor.YouwouldcreatetheFanclass,andtheninheritfromitFanForHardDrive,FanForAir
Conditioner,andFanForFireSuppression.Eachcallerlaunchesitsspecificcalleeactor.AllofthemainFanclass'codeisshared,but
whenitcomestimetosendmessages,theFanclasshasadynamicdispatchmethodfordoingthesending,andeachofthechildren
overridesthatmethodtosendthemessageappropriateforitscaller.Eachcalleeisstillcoupledtoaspecificcaller,butthesystemasa
wholeisflexibletoaccommodatenewcallertypes.
3.TheZeroCouplingSolutionInordertomakethecalleeactorindependentfromthecaller,thecallermusttellthecalleewhattypesof
messagestosendsothecalleeavoidspickingatypeitself.Thebestimplementationofthissolutionhasthecallerrecordamessageinto
thecalleeatthetimethecalleeislaunched.ThecalleeprovidesaSet<Type>Message.vimethod,where<Type>istheparticularevent
thatwilltriggerthemessagetobesent.Thecallersetstheexactmessageitwantstoreceivewhenthiseventoccurs.Whentheevent
happens,thecalleesendsthechosenmessage,withoutanyknowledgeofwhatkindofcallerisreceivingthatmessage.
OftenthecalleewilldefineanabstractMessageclassthatitusesastheinputtypeforSet<Type>Message.vi.Callerscreatetheirownspecificchildof
thisabstractclass.ThissetupgivesthecalleeawaytosetdataintothemessagethroughtheAPIdefinedbytheabstractclass,andgivesthemessage
awaytodeliverthatdatainaformthecallercanconsumethroughthevariousoverloadandextensionVIs.

ConsiderationsforImplementation
DebuggingActors
Everyactorrunsonitsown.Stoppingoneactorwon'tstoptheothersunlessyouhavesetupmessagestogothroughthetreeandshuteveryonedown.
Ifyouworkwiththeframeworkforanytimeatall,youwillatsomepointaccidentallyleaveanactorrunningwithoutitspanelopen.YourVIHierarchy
willbelockedbecauseitisrunning,butthere'sabsolutelynowayyou'llbeabletogetthatActorCore.vitopopopensoyoucanclicktheAbortbutton.
Therearetoolstohelpwiththisfrustratingsituation.
Thefirstquickworkaroundistocloseyourprojectandreopenit.YoudonothavetorestartLabVIEWaslongasyou'reworkinginsideaproject.
ClosingtheprojectwillabortalltherunningVIsinthatproject.
AbettersolutionistousetheoptionalinputonLaunch<X>Actor.viforOpenActorCorefrontpanel?(F).WiringTruetothisinputwillmakethe
frontpanelpopopenwhentheactorislaunched,givingyouaccesstothatactor'sownAbortbutton.Usingthisterminalinreleasecodewillreturnan
error(forreasonsexplainedintheonlinehelp),butwhiledebugging,thiscanbeamajorheadachesaver.
Asfarasdebuggingtheactuallogicofyourapplications,figuringoutwhereagivenmessagecamefromandwhetherornotMessageAonActorXwas
handledbeforeorafterMessageBonActorYcanbetricky.Beforeyoutrybuildingsomesortofeventloggingsystem,pleasecheckouttheDesktop
ExecutionTraceToolkitortheRealTimeExecutionTraceToolkitfromNationalInstruments.ThistoolhasdeepknowledgeofLabVIEWanditsAPIs,
givingyouinsightintoexecutionordering,memoryallocationanderrorpropagation.Ifyoudonothaveaccesstothesetoolkits,youmayfindthese
"timingprobes"useful.

ActorsinLibraries
UselibrariestomanageanddistributeyourActorclasses.Inadditiontothechildactorclass,thelibraryshouldcontainmostmessagesthattargetthat
actorandanyadditionaltightlycoupledclasses,suchaconfigurationobjectfortheactor(refertotheConfiguringActorssection,below),orthe
componentobjectsofacomposition.
YoumayopttobundleafamilyofActorsinasinglelibrary,especiallywherethatfamilysharesasinglesetofmessages.Bundlingmessagesinthe
librarygivesyoutheoptiontomarksomemessagesasprivatethisshouldbedoneforanymessagesthatareusedexclusivelybyclassesinyour
library,suchasmessagesthattheactorsendstoitselffromitsownActorCore.vi.
BecausealibraryinLabVIEWalwaysloadsallofitscontainedlibrariesintomemory,youshouldpackageintoyourlibraryonlythosemessageclasses
thatarenecessaryfortheactoritselftooperateoraresocommonlyusedastowarrantincluding.TheActorFrameworklibraryitselfdoesnotinclude
theBatch,Reply,andSelfAddressedMsgbecausetheyareoptionalcomponentsoftheframeworkandyoucanwritemanyapplicationsthatuseno
suchmessages.

ConfiguringActors
Often,youwanttoconfigureanactorwithdatafromelsewhereinthesystem,suchasinaconfigurationfile.BeforecallingLaunch<X>Actor.vi,you
canusethemethodsoftheactorclasstodirectlysetvaluesintotheactorobject.AftercallingLaunch<X>Actor.vi,youcangivedatatotheactor
objectthroughitsmessagequeues.Althoughyoucouldcreatemultiplemessagestosetindividualfieldsoftheactor,considercreatingasingle
Configurationclassthatencapsulatestheconfigurationinformation.Youcansettheconfigurationobjectthroughnormalmethodcalls,thenpassa
singleconfiguremessagetotheActor.These"largeblocksofdata"messagesshouldbereservedonetimeinitializationoftheobject,notforupdating
theobjectwhileyourapplicationisrunning.Whilerunning,youshouldusemessagesthatupdateonlythefieldsthathavechangedratherthan
rebroadcasttheentireobject.
Generally,theActorshouldneverprovideitsConfigurationasreturneddata,asthiscanleadtoraceconditions.RefertotheAvoidGetandSet
Messagessection,belowformoreinformation.Ifyouwanttocacheconfigurationdatafromashutdownactor,obtainthatdatafromthefinalvaluethe
actorreturnedintheLastAckmessage.TheactormayhaveaGetConfiguration.viwhichissimplynotexposedasamessage.

ImplementingActorsComposedofMultipleActors
(Composition)
InLabVIEW,adataobjectcanbedescribedcomposedofotherdataobjectswhenthoseotherobjectsarepartofitsprivatedata.Actorobjectsare
generallyonlyaccessiblethroughtheirmessagequeuesinthiscase,anobjectiscomposedofotheractorswhenithastheactors'messagequeuesas
partofitsprivatedata.Generally,thecomposedobjectwillitselfbeanactor,hereaftercalledthecalleractor.Thecomponentsarecalleeactors.There
aretwostylesofcalleractors:compositionsandaggregations.
Incompositions,thecalleractorisresponsibleforcreatinganddestroyingitsnestedactors.Thestandardimplementationistocreate,configureand
launchthenestedactorsintheActorCore.vi,priortostartinganyWhileLoopsorinvokingtheCallParentnode.ThecalleractorstorestheMessage
EnqueuerreturnedbyLaunchNestedActor.viforeachcomponentaspartofitsprivatedata.YouwillneedtoeitherusetheAutostop?feature
oroverrideStopCore.viinthecallertosendstopmessagestoeachcalleesotheyallshutdowntogether.
Aslightvariationonthisstylehasthecalleractorcreateandlaunchitsnestedactorsdynamicallyinresponsetoamessagereceived.Themessage
mightcontainjustconfigurationdataforthenestedactororitmightcontainthenestedactoritself(rememberthatactorsarebyvalueobjectsthatare
passedaroundasdataasneeded).Regardless,whenyourcalleractorlaunchesthesenestedactors,itfollowsthesamegeneralpatternasthestatically
launchednestedactorsdescribedabove.

AvoidGetandSetMessages
file:///D:/%23%23Trainings/LV/OOP_other/OOP_ARCHITECTURES/%23AF/my_AF_test_LV_2014/documentation/Actor%20Framework%20Whitepaper.h 4/5

2016.03.22.

ActorFrameworkWhitepaper

AvoidcreatingmessagesormessagepairsthatretrieveanattributefromanActor,modifyit,andreturnittotheActor.Thesetypesofoperationscan
introducethesamekindofresourcecontentionissuesasseenwithDataValueReferences(DVR)orfunctionalglobals.Worse,theyopenthedoorto
raceconditions.
Anactorrunsaparalleltask.IfyourGet/Setoperationconsistsoftwomessages,thentheActorcontinuestorunbetweenyourGetandSetmessages.
Anothertaskcouldaccessandmodifythesameattributeconcurrentlycausingaracecondition.
IfyourGet/Setoperationconsistsofasingle(probablyReplyMsgtype)message,thenyouhavelockedtheActorforthedurationofyouroperation.If
yourcallerattemptstoaccessyourActoraspartofyourmodifyoperation,yourapplicationwilldeadlock.Itisappropriate,ofcourse,foracallertosend
amessagerequestinganupdate(orregularseriesofupdates)fromanestedactor.Itisalsoappropriateforacallertopushanupdatetothenested
actor.Issuesonlyarisewhenyoulogicallylinkthegetandsetoperationsthatis,whenyougetattributesforthepurposeofmodifyingandreturning
them.

BenefitsoftheActorFramework
TheActorFrameworkprovidesnumeroustangiblebenefits.Itissignificantlymoreflexibleandextensiblethantraditionalstatemachinearchitectures,
andissaferandmoreefficientthanbyreferenceclasshierarchies.
ThepatternissimilartothefunctionalityprovidedbyabyreferenceclassbecausethedesignpermitsustotreatanActor'sReceiveQueueasahandle
totheActor.Otherbyreferencedesignsrelyonsomecontainertype,likedatavaluereferences(DVRs)orsingleelementqueues(SEQs)tocreatedata
thatissharedbetweentwoindependentVIs.Whileeffective,thisapproachhasthepotentialforraceconditionsanddeadlocks,especiallyifthereare
multiplebyreferenceobjectsinstantiatedinthesystem.Furthermore,certainoperationsthatareroutineinlanguageswithnativebyreferencesupport
arecumbersomeorevenprohibitedintheLabVIEWenvironment.TheActorFrameworkavoidsmanyoftheseshortcomingsbyfocusingonan
asynchronousinfrastructureinsteadoftryingtoreplicatethebyreferencepatternsofotherlanguages.

MoreExtensibleandReusableCode
TheActorFrameworkcreatesmorepotentialforcodeextensionandreusethantraditionalstatemachines.AchildActorcanreuseitsparent's
functionalityinthreeways:
1.Tochangeaparent'sbehavior,useachildwithanoverridemethod.
2.Toaddbehaviortoaparent,extendtheparentbyaddingnewmethodstoachild.
3.Togivetheparent'scontrollogicadditionalcontrollogic,decorate2 theActorCore.viwithanaddedcontrolloop.
Messagesarereusablewithinaclasshierarchy,soamessagethatworksonaparentstillworksonachild.Inaddition,messagesthemselvesare
inheritable,whichcansignificantlysimplifymessagesenders.Finally,sincemessagesarestronglytyped,theyreducetherisksassociatedwiththe
untypedmessagestypicallyusedinqueuedrivenstatemachines.

ActorsObjectsAreTestable
YoucantestmanyactorswithoutlaunchingtheActorCore.AnyofthememberVIsoftheactorclasscanberundirectly.Thosethatdonotattemptto
sendrepliestootheractorscanbetestedinisolationjustlikeanyotherVI,withouthavingtocreatetheSelfandCallerqueues.Youcanverifythe
resultingstateofanactorobjectbycomparingittoanotherinstanceofaknownvalue,justasyoucancheckthecontentsofaLabVIEWcluster.This
greatlyfacilitatesautomatedtesting.
Ifamethoddoescommunicatewithanotheractor,youwillneedtoinitializetheSelfandCallerqueues.YoucanuseaVIfoundondiskcalled:
<vilib>\ActorFramework\Actor\InitActorQueuesFORTESTINGONLY.vi
Thisfunctionprovidesabackdoorforsettingthequeuesinsidetheactor,whicharenormallyprivate,soyoucanmockupanactorandtestwhether,
givenaparticularinputmessage,itreturnstheexpectedresultmessages.
YoucanfittheActortoatestharnessorperhapsaTestStandsequence.TheharnesscaninvoketheActor'svariousmethods,andyoucancomparethe
resultstoexpectedvaluesintheformofActorinstancesofknownstates.IftheActorincorporatesauserinterfaceintoitsActorCore,youcanpassthe
referencetotheharnessintotheActorinsteadofthereferencetotheActorCore,andverifyresultsbycheckingthevaluesofupdatedcontrolsand
indicators.Notethisishardertodoifyouhaveoptedtoemployusereventsforfrontpanelupdates,whicharguesagainstthatmethod.Iftheuser
interfaceassociatedwiththeActorisaseparateVI,youcantesttheActoranduserinterfaceindifferentharnesses.
TheVITesterfromJKIisasystemthatisparticularlygoodatprovidingtestingforallobjectorientedapplications,includingtheActorFramework.You
caninvestigatethattoolhere.

GuaranteedDeliveryofStopMessage
Acommonprobleminothermessagingframeworksoccursduringshutdown.Onecomponentsendsthestopmessagetoanothercomponentandthen
quits.BecausearefnuminLabVIEWhasthesamelifetimeastheVIthatcreatedit,manyframeworkshaveaproblemthatthequeuecanbedestroyed
beforetheothercomponentreceivesthemessage.Manygotoelaborateextremestoensuremessagedeliverybeforethefirstcomponentexits.Withthe
ActorFramework,eachcomponentcreatesitsownreceivequeue,sothatqueuehasthesamelifetimeasthereceiver,notthesender.Thatmeansthat
anycomponentcallerorcalleecansendthestopmessageandthenshutitselfdownwithoutworryingaboutthemessagenotbeingdelivered.

Questions?
TheActorFrameworkcommunityforum
Downloadexpansionsandvariationsoftheframework

Footnotes
1.AlsoknownasaQueueDrivenMessageHandler.
2."Decorate"isnotanindustrystandardterminthiscontext.Itdescribesthisthirdaspectofreusethatisuniquetotaskframeworks.
Copyright
2012,2013,2014NationalInstruments.Allrightsreserved.
Forcopyrightnotices,conditions,anddisclaimers,includinginformationregardingcertainthirdpartycomponentsusedinLabVIEW,refertothe
CopyrighttopicoftheLabVIEWHelp.
Trademarks
LabVIEW,NationalInstruments,NI,ni.com,LabVIEW,theNationalInstrumentscorporatelogo,andtheEaglelogoaretrademarksofNational
InstrumentsCorporation.RefertotheTrademarkInformationatni.com/trademarksforotherNationalInstrumentstrademarks.
Patents
ForpatentscoveringtheNationalInstrumentsproducts/technology,refertotheappropriatelocation:HelpPatentsinyoursoftware,thepatents.txt
fileonyourmedia,ortheNationalInstrumentsPatentNoticeatni.com/patents.

file:///D:/%23%23Trainings/LV/OOP_other/OOP_ARCHITECTURES/%23AF/my_AF_test_LV_2014/documentation/Actor%20Framework%20Whitepaper.h 5/5

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy