Anda di halaman 1dari 61

ni.

com

What a Software Architect Needs


to Know When Using the Actor
Framework
David Staab, CLA
Staab Engineering
Stobber on LAVA

ni.com

Dave Snyder, CLA


Endeavor Engineering
Daklu on LAVA

Two-Part Session

Part 1: Principles of Actor Oriented Design

Learn how to think about actors


Learn how to apply the actor model in general LabVIEW code

Part 2: Making the Actor Framework work for you

ni.com

Learn how to customize framework to achieve common design


goals
3

Part I
Fundamentals of Actor-Oriented Design (AOD)
Actor Model Theory

What is the Actor Model?


Three elements of the model
Principles that apply to all Actors
Actor system topologies

Applying AOD in LabVIEW


Mapping model elements to code
Tips when implementing Actors

ni.com

Actor Model Theory

ni.com

Actor Theory

What is the Actor Model?


The Actor model in computer science is a
mathematical model of concurrent computation
that treats actors as the universal primitives of
concurrent digital computation.
Wikipedia

Translation: Its a way of thinking about and


understanding concurrency.

ni.com

Actor Theory

Elements of the Actor Model

An encapsulation of data,
procedures, and threads

Actor

Msg

Actor

Message
Any information passing
between actors

Addr

Address
A label indicating message
destination

ni.com

Actor Theory

Actor Principle #1

Actors can receive any message at any time

An actor has no control over


who has its address

Each actor sends msgs on


its own schedule

A1
A1

A2

A1
A1

Actors must react to unexpected


messages gracefully
ni.com

!!

A3

A4

Actor Theory

Actor Principle #2
Actors are self-deterministic
Ways to think about it
The actor is responsible for itself
Messages are always requests, never commands
Things are not done to an actor; an actor does things
to itself
If a turkey were an actor, come Thanksgiving we
would ask it to chop off its own head.
Carl Hewitt (paraphrased)

ni.com

Actor Theory

Actor System Topologies: Starter Options

Direct

Hierarchical

A1
A2
Advantages(?):
Easy to implement
Doesnt require much
A4
A3
planning
Feels very efficient

A1
Advantages:
Promotes encapsulation
A3
A2
Easier to reason about
the behavior
Better scalability
A4
A5

A5

ni.com

10

Actor Theory

Summary

Actors encapsulate data, procedures, and


threads

Actors cannot predict the next message

Actor Design != Actor System Design

ni.com

11

Applying AOD to LabVIEW

ni.com

12

AOD in LV

Implementing Messages: Options


Command
Pattern

Name/Data

Msg
Do.vi

MyMsg
Do.vi

Commonly implemented as
clusters
Msgs are stringly typed
Message and msg handling
code are separate

Requires classes to
implement
Msgs are strongly typed
Message contains msg
handling code

Each option has natural strengths.


Neither option has insurmountable technical limitations.
ni.com

13

AOD in LV

Implementing Addresses

Addresses = Message Transport


(Queue, User Events, etc.)

but Dave
An address defines a location. Transports move
messages around. Theyre not the same.

The Actor Model is a model

ni.com

14

AOD in LV

Implementing Actors
Actor Brain = Message Handling Loop (MHL)

DQ Msg

= QMH?

Names convey information about how


the thing is used. Actor != QMH

ni.com

15

AOD in LV > Actors

Sidebar: Comparing Common QMH and Actor


Common QMH

Actor

Dumb parallel process

Smart parallel process

Focus on sequencing
procedures

Focus on accomplishing
tasks

Puts responsibility on msg


sender (developer)

Takes responsibility for itself

Often thread unsafe

Thread safe

Scales poorly

Scales well

Encourages writing code


quickly

Encourages writing code


robustly

ni.com

16

AOD in LV > Actors > MHL

Tip #1

Each MHL is a new actor

ni.com

Behaviors define actor, not artifacts (VI, lvlib, etc.)


Multiple MHL on one block diagram is fine
MHL is the actors public interface
Usually maintains all actor state data

17

AOD in LV > Actors > MHL Tip 1

UI Block Diagram

Four Actors

ni.com

18

AOD in LV > Actors > MHL

Tip #2

Each actor entails


development overhead
All actors need

Exit conditions
Error handling

Implement these features FIRST

ni.com

19

AOD in LV > Actors > MHL Tip 2

Actor Development Overhead


My MHL Template

DQ Msg

Create
Queue
ni.com

Destroy Queue

20

AOD in LV > Actors > MHL

Tip #3

Not All Loops Are Actors

Some processes are not conducive to MHL

Delegate to Helper Loops

ni.com

E.g. Continuous processes, periodic processes


No message handler
Limited self-determinism
Does one task well
Not a shared resource

21

AOD in LV > Actors > MHL Tip 3

Helper Loop Metronome

ni.com

22

AOD in LV > Actors > MHL

Tip #4

Actors work best when the


MHL has to wait

Msg processing time << Time between msgs


MHL should handle every message instantly

Dont use it as a job queue


Priority messages are unnecessary

Manipulating the message transport


is a Code Smell
ni.com

23

AOD in LV > Actors > MHL Tip 4

Helper Loop Job Processor

ni.com

24

AOD in LV > Actors

Message Handling Loop Tips

Each MHL is a new actor


Each actor entails development overhead
Not all loops are actors Helper Loops
Actors work best when the MHL has to wait
If the MHL is the actors brain, helper loops and
sub actors are the arms and legs doing the
heavy lifting.

ni.com

25

If nothing else, remember this


AOD requires changing how you think

Its not the same as QMH/QSM thinking

Dont try to do too much in your MHL

Delegate to sub actors and helper loops

Actors can receive any message at any time

ni.com

Make sure you implement them that way

26

Part II
Making the Actor Framework Work for You
1.
2.
3.
4.
5.
6.
7.

ni.com

Actor Framework review


How to communicate with actors
How to implement state
How to handle or report errors
How to stop actors
How to debug actors
How to deploy actors

27

Actor Framework Review

ni.com

28

Actor Framework Review

Actor Framework Features

Uses Inversion of Control (IOC) to guarantee safe


execution

Several features for advanced applications

Priority Queues for inter-actor communication


o

Actors address is its queue refnum

MHL provided by the framework


Actors are launched dynamically
Actors are multi-instanced
Default error handling scheme

All these features come with the framework; cannot


smorgasbord!

ni.com

29

Actor Framework Review

Messaging Actors

MHL uses the Command Pattern; messages are objects

ni.com

All messages inherit from

AF:Message.lvclass

30

Actor Framework Review

Common Actor Life Cycle (part 1)


= Framework component
= Optional override

ni.com

31

Actor Framework Review

Common Actor Life Cycle (part 2)


= Framework component
= Optional override

ni.com

32

How to Communicate with Actors

ni.com

33

How to Communicate with Actors

VI Call Hierarchy

Senders are Coupled to Receivers

No way to completely decouple


actors in AF

Msg class library always links them


in at least one direction.
Actor 1.Method A.vi

ni.com

34

How to Communicate with Actors

Loosen Coupling via Actor Hierarchy

Design Msg:Do.vi to work on abstract actor type

If message has no payload, could be Actor.lvclass


If message has payload, need abstract actor with method

Allows sender to choose its receiver


Msg:Do.vi

ni.com

35

How to Communicate with Actors

Loosen Coupling via Message Hierarchy

Abstract data (payload)


Concrete method (action)

Can change message on


receivers interface at runtime

Allows receiver to choose


message

ni.com

36

How to Communicate with Actors

Messaging Outside the Framework

Frameworks tend to be viral in a design


AF actors send messages to callers via priority queue.
Msg:Send.vi

ni.com

AF actors want their callers to be AF actors.

Non-AF caller of an AF actor must either ignore messages or


implement its own MHL for the priority queue.
37

How to Communicate with Actors

Minimal MHL for non-AF caller

MyCallerMHL.vi

ni.com

38

How to Communicate with Actors

Calling Actor Methods Synchronously

Reply Msg.lvclass allows synchronous code to call


actors (command/response)

Timeout condition only tells whether actor processed msg

Condition

Indication

Error
~Error &&

Msg not sent


Timeout

~Error && ~Timeout

ni.com

Msg not executed or failed


??? (Executed? Cached? Ignored?)

39

How to Communicate with Actors

Enhanced Reply Msg


MyReplyMessage:Do Core.vi

Example:
Add ACK
to Reply
MyActor:Shut Down.vi

ni.com

40

How to Communicate with Actors

Enhanced Reply Msg Benefits

Add ACK output from Reply Msgs to report whether


message executed.
Condition

Indication

Error
~Error &&

Msg not sent


Timeout

~Error && ~Timeout &&

Msg not executed or failed


ACK

Msg executed normally

~Error && ~Timeout && ~ACK

Msg ignored or cached

ACK also reports whether other data in Reply output is


valid.
Condition

Indication

~ACK

Reply value invalid

ACK
ni.com

Reply value valid


41

How to Implement State

ni.com

42

How to Implement State

Working with Shared Reentrancy

All AF actors are launched dynamically using ACBR node

LV uses a pool of clones for shared reentrant VIs

Msg:Do.vi is shared reentrant So are your actor methods

No certainty in which clone will be used on each call

Must avoid storing state in a shared reentrant method.


Cannot use these elements:

ni.com

Uninitialized shift registers


Feedback nodes
UI code that assumes Front Panel will be in default state
<vi.lib> functions that cache state

43

How to Implement State

Store Actor State in Object Parameters

Object wire is stored in MHLs shift register

Every message method has access to wire

state data
non-state data

Recommend using clusters to organize complex object


data

ni.com

44

How to Implement State

Remove State from SubVIs


<vi.lib> Peak Detector.vi

ni.com

45

How to Implement State

Remove State from SubVIs

Stateless Peak Detector.vi

ni.com

46

How to Implement State

Remove State from SubVIs

MyActor:Find Peaks.vi

ni.com

47

How to Handle or Report Errors

ni.com

48

How to Handle or Report Errors

Default Framework Behavior

All message errors are handled by the framework.


1.
2.
3.
4.

Message method generates error


Handle Error.vi always stops the actor (by default)
Last Ack Msg is sent to caller (not shown)
Caller reads error from LA Msg and throws it to itself
o

GOTO 1
AF:Actor:Actor Core.vi

AF:Actor:Handle Last Ack Core.vi

ni.com

49

How to Handle or Report Errors

Customizing Error Handling


Define non-default behaviors by overriding framework VIs:

Handle Error.vi

Handle Last Ack Core.vi

Report errors to a central handler or logger


Clear locally-scoped errors
Do not insert callees error into own error path
Re-launch callee to attempt graceful error recovery

Make this default for your actors with an override class

e.g. MyActor.lvclass AF_Overrides.lvclass Actor.lvclass

This does not handle errors in helper loops!

ni.com

50

How to Stop Actors

ni.com

51

How to Stop Actors

How the Framework Stops an Actor


AF:Stop Msg:Do.vi

Stop Msg.lvclass:Do.vi inserts


an error into the MHL

1.

Handle Error.vi stops the actor


and clears error 43

2.

Error 43 never reported by actor


to its caller

Error 43 is a standard code used by <vi.lib> functions

43: Normal Stop


1608: Emergency Stop

Operation canceled by user


e.g. Open/Create/Replace File.vi: If user cancels a File Browse
operation, actor will stop without error.

Error 1608 is not cleared: all actors in call chain will stop

ni.com

53

How to Stop Actors

Default Stopping Handshake

Framework defines a handshake for stopping an actor

Common design sends Stop Msg to callees in Stop


Core.vi

Caller sends Stop Msg, actor stops asynchronously


Actor sends Last Ack Msg to caller after it stops

Stop Core executes after MHL breaks


Caller cannot listen for Last Ack Msg from stopped callees
If Last Ack Msg carries an error, caller will not pass error up the
call chain!

Better design avoids stopping caller until Last Ack Msgs


arrive from all callees.

ni.com

54

How to Stop Actors

Improved Stop Handshake

MyActor:Handle Error.vi

MyActor:Handle Last Ack Core.vi

ni.com

55

How to Debug Actors

ni.com

56

How to Debug Actors

The Framework Makes Debugging Harder

Many debugging challenges caused by two facts:

1.

Breakpoints do not work normally on VI clones

2.

3.

ni.com

AF dynamically launches every actor.


AC.vi and Msg:Do.vi are shared reentrant

Saved breakpoints cant be disabled on clones


Breakpoints set on a clone at run-time dont work

Probes set on a reentrant VIs wire (prior to run) dont


show clone data (while running)
Execution highlighting and probes cause bugs and
crashes when used on reentrant VIs in LVRT.
57

How to Debug Actors

Debugging Workarounds
1.

If actor has no helper loop, develop and test class


without launching it. When tests pass, launch using AF.

2.

Wire True to Show Front Panel input on Launch


Actor.vi

3.

Inspect clone using Highlight Execution and probes


Cant be used on AC.vis inserted into a subpanel

Use NI Desktop Execution Trace Toolkit v2013

ni.com

Can test as a multi-instance class by splitting the wire


Infeasible if class sends AF messages inside its methods

Generate events when actors initialize, start execution, handle an


error, receive a Last Ack Msg, receive a Stop Msg, etc.
Add these traces to your framework override
58

How to Deploy Actors

ni.com

59

How to Deploy Actors

Deploying Applications and Compiled Libraries

AF actors are launched dynamically, so an application


needs a launcher VI.

If app uses AF actors for the UI, normally want to close


the launcher when UI finishes initialization.

Might include extra features like error reporting/logging,


controlled shutdown, RPC or CLI, etc.

Make the launcher a Splash Screen

AC.vi is called by ACBR node, so app builder might strip


its front panel from the build.

ni.com

AF requires all AC.vi front panels to execute.


Access a front panel property or value to prevent this.
60

How to Deploy Actors

Deploying Applications and Compiled Libraries

AF does not work natively with LVLIBP (Packed Project


Libraries)

Must modify the framework


v4.0 can be modified to work, but not v4.1 (shipping with LV)

See NI Community for details:


https://decibel.ni.com/content/message/49089#49089

ni.com

61

Thanks!

Dave Snyder
dave@meksys.com
David Staab
david@staabengineering.com

ni.com

62