source: doc/theses/colby_parsons_MMAth/text/actors.tex @ 2d831a1

ADTast-experimental
Last change on this file since 2d831a1 was 2d831a1, checked in by caparsons <caparson@…>, 14 months ago

added various small edits and resolved some action items

  • Property mode set to 100644
File size: 67.3 KB
Line 
1% ======================================================================
2% ======================================================================
3\chapter{Actors}\label{s:actors}
4% ======================================================================
5% ======================================================================
6
7% C_TODO: add citations throughout chapter
8Actors are a concurrent feature that abstracts threading away from a user, and instead provides \gls{actor}s and messages as building blocks for concurrency.
9Actors are another message passing concurrency feature, similar to channels, but with more abstraction.
10Actors enter the realm of what is called \gls{impl_concurrency}, where programmers can write concurrent code without having to worry about explicit thread synchronization and mutual exclusion.
11The study of actors can be broken into two concepts, the \gls{actor_model}, which describes the model of computation and the \gls{actor_system}, which refers to the implementation of the model in practice.
12Before discussing \CFA's actor system in detail, it is important to first describe the actor model, and the classic approach to implementing an actor system.
13
14\section{The Actor Model}
15The actor model is a paradigm of concurrent computation, where tasks are broken into units of work that are distributed to actors in the form of messages \cite{Hewitt73}.
16Actors execute asynchronously upon receiving a message and can modify their own state, make decisions, spawn more actors, and send messages to other actors.
17The actor model is an implicit model of concurrency.
18As such, one strength of the actor model is that it abstracts away many considerations that are needed in other paradigms of concurrent computation.
19Mutual exclusion, and locking are rarely relevant concepts to users of an actor model, as actors typically operate on local state.
20
21\section{Classic Actor System}
22An implementation of the actor model with a community of actors is called an actor system.
23Actor systems largely follow the actor model, but differ in some ways.
24While the definition of the actor model provides no restrictions on message ordering, actor systems tend to guarantee that messages sent from a given actor $i$ to actor $j$ will arrive at actor $j$ in the order they were sent.
25Another way an actor system varies from the model is that actors are often allowed to access non-local state.
26When this occurs it can complicate the implementation as this will break any mutual exclusion guarantees given by accessing only local state.
27
28\begin{figure}
29\begin{tabular}{l|l}
30\subfloat[Actor-centric system]{\label{f:standard_actor}\input{diagrams/standard_actor.tikz}} & 
31\subfloat[Message-centric system]{\label{f:inverted_actor}\raisebox{.1\height}{\input{diagrams/inverted_actor.tikz}}} 
32\end{tabular}
33\caption{Classic and inverted actor implementation approaches with sharded queues.}
34\end{figure}
35
36\section{\CFA Actors}
37Actor systems \cite{} have often been implemented as an actor-centric system.
38As such they are constructed as a set of actors that are scheduled and run on some underlying threads.
39Each actor has their own queue for receiving messages, sometimes called a mailbox.
40When they receive messages in their mailbox, actors are moved from idle to ready queues and then scheduled on a thread to run their unit of work.
41This approach can be implemented with a global queue of actors, but is often implemented as each worker thread owning a queue of actors.
42This is known as sharding the actor queue, which is done to decrease contention across worker threads.
43A diagram of an actor-centric system with a sharded actor queue is shown in Figure \ref{f:standard_actor}.
44
45% cite parallel theatre and our paper
46The actor system in \CFA is instead message-centric, an uses what is called an inverted actor system \cite{}.
47In this inverted actor system instead of each worker thread owning a queue of actors, they each own a queue of messages.
48This system is called inverted since in this scheme, actors belong to a message queue, whereas in the classic approach a message queue belongs to each actor.
49Since multiple actors belong to each message queue, messages to each actor are interleaved in the queue.
50In this scheme work is consumed from their queue and executed by underlying threads.
51In High-Performance Extended Actors \cite{} this inverted model is taken a step further and the message queues are sharded, so that each worker now instead owns a set of queues.
52A diagram of an inverted actor scheme with a sharded message queue is shown in Figure \ref{f:inverted_actor}.
53The arrows from the message queues to the actors in the diagram indicate interleaved messages addressed to each actor.
54
55The actor system in \CFA builds on top of the architecture laid out in High-Performance Extended Actors \cite{} and adds the following contributions:
56
57\begin{enumerate}[topsep=5pt,itemsep=3pt,parsep=0pt]
58\item
59Provides insight into the impact of envelope allocation in actor systems.
60In all actor systems dynamic allocation is needed to ensure that the lifetime of a unit of work persists from its creation until the unit of work is executed.
61This allocation is often called an envelope as it "packages" the information needed to run the unit of work, alongside any other information needed to send the unit of work, such as an actor's address or link fields for a list.
62This dynamic allocation occurs once per message sent.
63This is a large source of contention on the memory allocator since all these allocations occur concurrently.
64A novel data structure is used to consolidate allocations to improve performance by minimizing contention on the allocator.
65
66\item
67Introduces work stealing in the inverted actor system.
68Work stealing in actor-centric systems tends to involve stealing one or more actors.
69In the inverted system the notion of stealing queues is introduced.
70The queue stealing is implemented such that the act of stealing work does not contend with non-stealing actors that are saturated with work.
71
72\item
73Introduces and evaluates a timestamp based work stealing heuristic with the goal of maintaining non-workstealing performance in work-saturated workloads, and improving performance on unbalanced workloads.
74
75\item
76Improves performance of the inverted actor system using multiple approaches to minimize contention on queues, such as queue gulping and avoiding atomic operations.
77
78\item
79Provides a suite of safety and productivity features including static-typing, detection of erroneous message sends, statistics tracking, and more.
80\end{enumerate}
81
82\section{\CFA Actor Syntax}
83\CFA is not an object oriented language and it does not have run-time type information (RTTI).
84As such all message sends and receives between actors occur using exact type matching.
85To use actors in \CFA you must \code{\#include <actors.hfa>}.
86To create an actor type one must define a struct which inherits from the base \code{actor} struct via the \code{inline} keyword.
87This is the Plan-9 C-style nominal inheritance discussed in Section \ref{s:poly}.
88Similarly to create a message type a user must define a struct which \code{inline}'s the base \code{message} struct.
89
90\begin{cfa}
91struct derived_actor {
92        inline actor;      // Plan-9 C inheritance
93};
94void ?{}( derived_actor & this ) { // Default ctor
95        ((actor &)this){};  // Call to actor ctor
96}
97
98struct derived_msg {
99        inline message;  // Plan-9 C nominal inheritance
100        char word[12];
101};
102void ?{}( derived_msg & this, char * new_word ) { // Overloaded ctor
103        ((message &) this){ Nodelete }; // Passing allocation to ctor
104        strcpy(this.word, new_word);
105}
106
107Allocation receive( derived_actor & receiver, derived_msg & msg ) {
108        printf("The message contained the string: %s\n", msg.word);
109        return Finished; // Return finished since actor is done
110}
111
112int main() {
113        start_actor_system(); // Sets up executor
114        derived_actor my_actor;         
115        derived_msg my_msg{ "Hello World" }; // Constructor call
116        my_actor << my_msg;   // Send message via left shift operator
117        stop_actor_system(); // Waits until actors are finished
118        return 0;
119}
120\end{cfa}
121
122The above code is a simple actor program in \CFA.
123There is one derived actor type and one derived message type.
124A single message containing a string is sent from the program main to an actor.
125Key things to highlight include the \code{receive} signature, and calls to \code{start_actor_system}, and \code{stop_actor_system}.
126To define a behaviour for some derived actor and derived message type, one must declare a routine with the signature:
127\begin{cfa}
128Allocation receive( derived_actor & receiver, derived_msg & msg )
129\end{cfa}
130Where \code{derived_actor} and \code{derived_msg} can be any derived actor and derived message types respectively.
131The return value of \code{receive} must be a value from the \code{Allocation} enum:
132\begin{cfa}
133enum Allocation { Nodelete, Delete, Destroy, Finished };
134\end{cfa}
135The \code{Allocation} enum is a set of actions that dictate what the executor should do with a message or actor after a given behaviour has been completed.
136In the case of an actor, the \code{receive} routine returns the \code{Allocation} status to the executor which sets the status on the actor and takes the appropriate action.
137For messages, they either default to \code{Nodelete}, or they can be passed an \code{Allocation} via the \code{message} constructor.
138Message state can be updated via a call to:
139\begin{cfa}
140void set_allocation( message & this, Allocation state )
141\end{cfa}
142
143The following describes the use of each of the \code{Allocation} values:
144
145\begin{description}
146\item[\LstBasicStyle{\textbf{Nodelete}}]
147tells the executor that no action is to be taken with regard to a message or actor with this status.
148This indicates that the actor will receive future behaviours, and that a message may be reused.
149
150\item[\LstBasicStyle{\textbf{Delete}}]
151tells the executor to call the appropriate destructor and then deallocate the respective actor or message.
152This status is typically used with dynamically allocated actors and messages.
153
154\item[\LstBasicStyle{\textbf{Destroy}}]
155tells the executor to call the object's destructor.
156The executor will not deallocate the respective actor or message.
157This status is typically used with dynamically allocated actors and messages whose storage will be reused.
158
159\item[\LstBasicStyle{\textbf{Finished}}]
160tells the executor to mark the respective actor as being finished executing.
161In this case the executor will not call any destructors or deallocate any objects.
162This status is used when the actors are stack allocated or if the user wants to manage deallocation of actors themselves.
163In the case of messages, \code{Finished} is no different than \code{Nodelete} since the executor does not need to track if messages are done work.
164As such \code{Finished} is not supported for messages and is used internally by the executor to track if messages have been used for debugging purposes.
165\end{description}
166
167For the actor system to gracefully terminate, all actors must have returned a status other than \code{Nodelete}.
168Once an actor's allocation status has been set to something other than \code{Nodelete}, it is erroneous for the actor to receive a message.
169Similarly messages cannot be safely reused after their related behaviour if their status is not \code{Nodelete}.
170Note, it is safe to construct a message with a non-\code{Nodelete} status since the executor will only take the appropriate allocation action after a message has been delivered.
171
172The calls to \code{start_actor_system}, and \code{stop_actor_system} mark the start and end of a \CFA actor system.
173The call to \code{start_actor_system} sets up the executor and worker threads for the actor system.
174\code{start_actor_system} has three overloaded signatures which all start the actor system, but vary in executor configuration:
175
176\noindent\code{void start_actor_system()} configures the executor with one underlying worker thread and processor.
177
178\noindent\code{void start_actor_system( size_t num_thds )} configures the executor with \code{num_thds} underlying processors and \code{num_thds} worker threads.
179It chooses amount of queue sharding as a function of \code{num_thds}.
180
181\noindent\code{void start_actor_system( executor & this )} allows the user to allocate, configure, and pass an executor so that they have full control of executor parameterization.
182Executor configuration options include number of worker threads, number of queues, number of processors, and a few other toggles.
183
184All actors must be created after calling \code{start_actor_system} so that the executor can keep track of the number of actors that have been allocated but have not yet terminated.
185
186All message sends are done using the left shift operater, \ie <<, similar to the syntax of \CC's output.
187The signature of the left shift operator is:
188\begin{cfa}
189Allocation ?<<?( derived_actor & receiver, derived_msg & msg )
190\end{cfa}
191
192An astute eye will notice that this is the same signature as the \code{receive} routine which is no coincidence.
193The \CFA compiler generates a \code{?<<?} routine definition and forward declaration for each \code{receive} routine that has the appropriate signature.
194The generated routine packages the message and actor in an \hyperref[s:envelope]{envelope} and adds it to the executor's queues via an executor routine.
195As part of packaging the envelope, the \code{?<<?} routine sets a function pointer in the envelope to point to the appropriate receive routine for given actor and message types.
196
197
198\section{\CFA Executor}\label{s:executor}
199This section will describe the basic architecture of the \CFA executor.
200Any discussion of work stealing is omitted until Section \ref{s:steal}.
201The executor of an actor system is the scheduler that organizes where actors behaviours are run and how messages are sent and delivered.
202In \CFA the executor lays out actors across the sharded message queues in round robin order as they are created.
203The message queues are split across worker threads in equal chunks, or as equal as possible if the number of message queues is not divisible by the number of workers threads.
204
205\begin{figure}
206\begin{center}
207\input{diagrams/gulp.tikz}
208\end{center}
209\caption{Diagram of the queue gulping mechanism.}
210\label{f:gulp}
211\end{figure}
212
213Each worker thread iterates over its own message queues until it finds one that contains messages.
214At this point the worker thread \textbf{gulps} the queue.
215A \textbf{gulp} is a term for consuming the contents of message queue and transferring them to the local queue of worker thread.
216After the gulp is done atomically, this allows the worker thread to process the queue locally without any need for atomicity until the next gulp.
217Messages can be added to the queue that was gulped in parallel with the processing of the local queue.
218Additionally, prior to each gulp, the worker non-atomically checks if a queue is empty before attempting to gulp it.
219Between this and the gulp, the worker avoids many potentially costly lock acquisitions.
220An example of the queue gulping operation is shown in Figure \ref{f:gulp} where a worker thread gulps queue 0 and begins to process it locally.
221
222To process its local queue, a worker thread takes each unit of work off the queue and executes it.
223Since all messages to a given actor will be in the same queue, this guarantees atomicity across behaviours of that actor since it can only execute on one thread at a time.
224After running behaviour, the worker thread looks at the returned allocation status and takes the corresponding action.
225Once all actors have marked themselves as being finished the executor initiates shutdown by inserting a sentinel value into the message queues.
226Once a worker thread sees a sentinel it stops running.
227After all workers stop running the actor system shutdown is complete.
228
229\section{Envelopes}\label{s:envelope}
230In actor systems messages are sent and received by actors.
231When a actor receives a message it executes its behaviour that is associated with that message type.
232However the unit of work that stores the message, the receiving actor's address, and other pertinent information needs to persist between send and the receive.
233Furthermore the unit of work needs to be able to be stored in some fashion, usually in a queue, until it is executed by an actor.
234All these requirements are fulfilled by a construct called an envelope.
235The envelope wraps up the unit of work and also stores any information needed by data structures such as link fields.
236To meet the persistence requirement the envelope is dynamically allocated and cleaned up after it has been delivered and its payload has run.
237
238One may ask, "Could the link fields and other information be stored in the message?".
239This is a good question to ask since messages also need to have a lifetime that persists beyond the work it delivers.
240However, if one were to use messages as envelopes then a message would not be able to be sent to multiple actors at a time.
241Therefore this approach would just push the allocation into another location, and require the user to dynamically allocate a message for every send, or require careful ordering to allow for message reuse.
242
243This frequent allocation of envelopes with each message send between actors results in heavy contention on the memory allocator.
244As such, a way to alleviate contention on the memory allocator could result in performance improvement.
245Contention was reduced using a novel data structure that is called a copy queue.
246
247\subsection{The Copy Queue}\label{s:copyQueue}
248The copy queue is a thin layer over a dynamically sized array that is designed with the envelope use case in mind.
249A copy queue supports the typical queue operations of push/pop but in a different way than a typical array based queue.
250The copy queue is designed to take advantage of the \hyperref[s:executor]{gulping} pattern.
251As such the amortized rutime cost of each push/pop operation for the copy queue is $O(1)$.
252In contrast, a naive array based queue often has either push or pop cost $O(n)$ and the other cost $O(1)$ since for at least one of the operations all the elements of the queue have to be shifted over.
253Since the worker threads gulp each queue to operate on locally, this creates a usage pattern of the queue where all elements are popped from the copy queue without any interleaved pushes.
254As such, during pop operations there is no need to shift array elements.
255An index is stored in the copy queue data structure which keeps track of which element to pop next allowing pop to be $O(1)$.
256Push operations are amortized $O(1)$ since pushes may cause doubling reallocations of the underlying dynamic sized array.
257
258% C_TODO: maybe make copy_queue diagram
259
260Since the copy queue is an array, envelopes are allocated first on the stack and then copied into the copy queue to persist until they are no longer needed.
261For a fixed message throughput workload, once the copy queues grow in size to facilitate the number of messages in flight, there are no longer any dynamic allocations occuring in the actor system.
262One problem that arises with this approach is that this array based approach will often allocate more storage than what is needed.
263Comparitively the individual envelope allocations of a list based queue mean that the actor system will always use the minimum amount of heap space needed and will clean up eagerly.
264Additionally, a workload with variable message throughput could cause copy queues to allocate large amounts of space to accomodate the peaks of the throughput, even if most of that storage is not needed for the rest of the workload's execution.
265
266
267To mitigate this a memory reclamation scheme was introduced.
268Initially the memory reclamation naively reclaimed one index of the array per gulp if the array size was above a low fixed threshold.
269This approach had a problem.
270The high memory usage watermark nearly doubled with this change! The issue with this approach can easily be highlighted with an example.
271Say that there is a fixed throughput workload where a queue never has more than 19 messages at a time.
272If the copy queue starts with a size of 10, it will end up doubling at some point to size 20 to accomodate 19 messages.
273However, after 2 gulps and subsequent reclamations the array would be size 18.
274The next time 19 messages are enqueued, the array size is doubled to 36! To avoid this issue a second check was added to reclamation.
275Each copy queue started tracking the utilization of their array size.
276Reclamation would only occur if less than half of the array was being utilized.
277In doing this the reclamation scheme was able to achieve a lower high watermark and a lower overall memory utilization when compared to the non-reclamation copy queues.
278However, the use of copy queues still incurs a higher memory cost than the list based queueing.
279With the inclusion of a memory reclamation scheme the increase in memory usage is reasonable considering the performance gains and will be discussed further in Section \ref{s:actor_perf}.
280
281\section{Work Stealing}\label{s:steal}
282Work stealing is a scheduling strategy that attempts to load balance, and increase resource untilization by having idle threads steal work.
283There are many parts that make up a work stealing actor scheduler, but the two that will be highlighted in this work are the stealing mechanism and victim selection.
284
285% C_TODO enter citation for langs
286\subsection{Stealing Mechanism}
287In this discussion of work stealing the worker being stolen from will be referred to as the \textbf{victim} and the worker stealing work will be called the \textbf{thief}.
288The stealing mechanism presented here differs from existing work stealing actor systems due the inverted actor system.
289Other actor systems such as Akka \cite{} and CAF \cite{} have work stealing, but since they use an classic actor system that is actor-centric, stealing work is the act of stealing an actor from a dequeue.
290As an example, in CAF, the sharded actor queue is a set of double ended queues (dequeues).
291Whenever an actor is moved to a ready queue, it is inserted into a worker's dequeue.
292Workers then consume actors from the dequeue and execute their behaviours.
293To steal work, thieves take one or more actors from a victim's dequeue.
294This action creates contention on the dequeue, which can slow down the throughput of the victim.
295The notion of which end of the dequeue is used for stealing, consuming, and inserting is not discussed since it isn't relevant.
296By the pigeon hole principle there are three dequeue operations (push/victim pop/thief pop) that can occur concurrently and only two ends to a dequeue, so work stealing being present in a dequeue based system will always result in a potential increase in contention on the dequeues.
297
298% C_TODO: maybe insert stealing diagram
299
300In \CFA, the actor work stealing implementation is unique.
301While other systems are concerned with stealing actors, the \CFA actor system steals queues.
302This is a result of \CFA's use of the inverted actor system.
303The goal of the \CFA actor work stealing mechanism is to have a zero-victim-cost stealing mechanism.
304This does not means that stealing has no cost.
305This goal is to ensure that stealing work does not impact the performance of victim workers.
306This means that thieves can not contend with victims, and that victims should perform no stealing related work unless they become a thief.
307In theory this goal is not achieved, but results will be presented that show the goal is achieved in practice.
308In \CFA's actor system workers own a set of sharded queues which they iterate over and gulp.
309If a worker has iterated over the queues they own twice without finding any work, they try to steal a queue from another worker.
310Stealing a queue is done wait-free with a few atomic instructions that can only create contention with other stealing workers.
311To steal a queue a worker does the following:
312\begin{enumerate}[topsep=5pt,itemsep=3pt,parsep=0pt]
313\item
314The thief chooses a victim.
315
316\item
317The thief starts at a random index in the array of the victim's queues and searches for a candidate queue.
318A candidate queue is any queue that is not empty, is not being stolen by another thief, and is not being processed by the victim.
319These are not strictly enforced rules.
320The candidate is identified non-atomically and as such queues that do not satisfy these rules may be stolen.
321However, steals that do not meet these requirements do not affect correctness so they are allowed and do not constitute failed steals as the queues will still be swapped.
322
323
324\item
325Once a candidate queue is chosen, the thief attempts a wait-free swap of the victim's queue and a random on of the thief's queues.
326This swap can fail.
327If the swap is successful the thief swaps the two queues.
328If the swap fails, another thief must have attempted to steal one of the two queues being swapped.
329Failing to steal is good in this case since stealing a queue that was just swapped would likely result in stealing an empty queue.
330\end{enumerate}
331
332Once a thief fails or succeeds in stealing a queue, it goes back to its own set of queues and iterates over them again.
333It will only try to steal again once it has completed two consecutive iterations over its owned queues without finding any work.
334The key to the stealing mechnism is that the queues can still be operated on while they are being swapped.
335This elimates any contention between thieves and victims.
336The first key to this is that actors and workers maintain two distinct arrays of references to queues.
337Actors will always receive messages via the same queues.
338Workers, on the other hand will swap the pointers to queues in their shared array and operate on queues in the range of that array that they own.
339Swapping queues is a matter of atomically swapping two pointers in the worker array.
340As such pushes to the queues can happen concurrently during the swap since pushes happen via the actor queue references.
341
342Gulping can also occur during queue swapping, but the implementation requires more nuance than the pushes.
343When a worker is not stealing it iterates across its own range of queues and gulps them one by one.
344When a worker operates on a queue it first copies the current pointer from the worker array of references to a local variable.
345It then uses that local variable for all queue operations until it moves to the next index of its range of the queue array.
346This ensures that any swaps do not interrupt gulping operations, however this introduces a correctness issue.
347If any behaviours from a queue are run by two workers at a time it violates both mutual exclusion and the actor ordering guarantees.
348As such this must be avoided.
349To avoid this each queue has a \code{being_processed} flag that is atomically set to \code{true} when a queue is gulped.
350The flag indicates that a queue is being processed locally and is set back to \code{false} once the local processing is finished.
351If a worker attempts to gulp a queue and finds that the \code{being_processed} flag is \code{true}, it does not gulp the queue and moves on to the next queue in its range.
352This is a source of contention between victims and thieves since a thief may steal a queue and set \code{being_processed} to \code{true} between a victim saving a pointer to a queue and gulping it.
353However, the window for this race is very small, making this contention rare.
354This is why the claim is made that this mechanism is zero-victim-cost in practice but not in theory.
355By collecting statistics on failed gulps due to the \code{being_processed} flag, it is found that this contention occurs ~0.05\% of the time when a gulp occurs.
356Hence, the claim is made that this stealing mechanism has zero-victim-cost in practice.
357
358
359\subsection{Queue Swap Correctness}
360Given the wait-free swap used is novel, it is important to show that it is correct.
361Firstly, it is clear to show that the swap is wait-free since all workers will fail or succeed in swapping the queues in a finite number of steps since there are no locks or looping.
362There is no retry mechanism in the case of a failed swap, since a failed swap either means the work was already stolen, or that work was stolen from the thief.
363In both cases it is apropos for a thief to given up on stealing.
364\CFA-style pseudocode for the queue swap is presented below.
365The swap uses compare-and-swap (\code{CAS}) which is just pseudocode for C's \code{__atomic_compare_exchange_n}.
366A pseudocode implementation of \code{CAS} is also shown below.
367The correctness of the wait-free swap will now be discussed in detail.
368To first verify sequential correctness, consider the equivalent sequential swap below:
369
370\begin{cfa}
371void swap( uint victim_idx, uint my_idx ) {
372        // Step 0:
373        work_queue * my_queue = request_queues[my_idx];
374        work_queue * vic_queue = request_queues[victim_idx];
375        // Step 2:
376        request_queues[my_idx] = 0p;
377        // Step 3:
378        request_queues[victim_idx] = my_queue;
379        // Step 4:
380        request_queues[my_idx] = vic_queue;
381}
382\end{cfa}
383
384Step 1 is missing in the sequential example since in only matter in the concurrent context presented later.
385By looking at the sequential swap it is easy to see that it is correct.
386Temporary copies of each pointer being swapped are stored, and then the original values of each pointer are set using the copy of the other pointer.
387
388\begin{cfa}
389// This routine is atomic
390bool CAS( work_queue ** ptr, work_queue ** old, work_queue * new ) {
391        if ( *ptr != *old )
392                return false;
393        *ptr = new;
394        return true;
395}
396
397bool try_swap_queues( worker & this, uint victim_idx, uint my_idx ) with(this) {
398        // Step 0:
399        // request_queues is the shared array of all sharded queues
400        work_queue * my_queue = request_queues[my_idx];
401        work_queue * vic_queue = request_queues[victim_idx];
402
403        // Step 1:
404        // If either queue is 0p then they are in the process of being stolen
405        // 0p is CForAll's equivalent of C++'s nullptr
406        if ( vic_queue == 0p ) return false;
407
408        // Step 2:
409        // Try to set thief's queue ptr to be 0p.
410        // If this CAS fails someone stole thief's queue so return false
411        if ( !CAS( &request_queues[my_idx], &my_queue, 0p ) )
412                return false;
413       
414        // Step 3:
415        // Try to set victim queue ptr to be thief's queue ptr.
416        // If it fails someone stole the other queue, so fix up then return false
417        if ( !CAS( &request_queues[victim_idx], &vic_queue, my_queue ) ) {
418                request_queues[my_idx] = my_queue; // reset queue ptr back to prev val
419                return false;
420        }
421
422        // Step 4:
423        // Successfully swapped.
424        // Thief's ptr is 0p so no one will touch it
425        // Write back without CAS is safe
426        request_queues[my_idx] = vic_queue;
427        return true;
428}
429\end{cfa}\label{c:swap}
430
431Now consider the concurrent implementation of the swap.
432\begin{enumerate}[topsep=5pt,itemsep=3pt,parsep=0pt]
433\item
434Step 0 is the same as the sequential example, and the thief stores local copies of the two pointers to be swapped.
435\item
436Step 1 verifies that the stored copy of the victim queue pointer, \code{vic_queue}, is valid.
437If \code{vic_queue} is equal to \code{0p}, then the victim queue is part of another swap so the operation fails.
438No state has changed at this point so no fixups are needed.
439Note, \code{my_queue} can never be equal to \code{0p} at this point since thieves only set their own queues pointers to \code{0p} when stealing.
440At no other point will a queue pointer be set to \code{0p}.
441Since each worker owns a disjoint range of the queue array, it is impossible for \code{my_queue} to be \code{0p}.
442\item
443Step 2 attempts to set the thief's queue pointer to \code{0p} via \code{CAS}.
444The \code{CAS} will only fail if the thief's queue pointer is no longer equal to \code{my_queue}, which implies that this thief has become a victim and its queue has been stolen.
445At this point the thief-turned-victim will fail and since it has not changed any state it just fails and returns false.
446If the \code{CAS} succeeds then the thief's queue pointer will now be \code{0p}.
447Nulling the pointer is safe since only thieves look at other worker's queue ranges, and whenever thieves need to dereference a queue pointer they check for \code{0p}.
448\item
449Step 3 attempts to set the victim's queue pointer to be \code{my_queue} via \code{CAS}.
450If the \code{CAS} succeeds then the victim's queue pointer has been set and swap can no longer fail.
451If the \code{CAS} fails then the thief's queue pointer must be restored to its previous value before returning.
452\item 
453Step 4 sets the thief's queue pointer to be \code{vic_queue} completing the swap.
454\end{enumerate}
455
456\begin{theorem}
457The presented swap is correct and concurrently safe in both the success and failure cases.
458\end{theorem}
459
460Correctness of the swap is shown through the existence of an invariant.
461The invariant is that when a queue pointer is set to \code{0p} by a thief, then the next write to the pointer can only be performed by the same thief.
462To show that this invariant holds, it is shown that it is true at each step of the swap.
463Step 0 and 1 do not write and as such they cannot invalidate the invariant of any other thieves.
464In step 2 a thief attempts to write \code{0p} to one of their queue pointers.
465This queue pointer cannot be \code{0p}.
466As stated above, \code{my_queue} is never equal to \code{0p} since thieves will only write \code{0p} to queue pointers from their own queue range and all worker's queue ranges are disjoint.
467As such step 2 upholds the invariant since in a failure case no write occurs, and in the success case, the value of the queue pointer is guaranteed to not be 0p.
468In step 3 the thief attempts to write \code{my_queue} to the victim's queue pointer.
469If the current value of the victim's queue pointer is \code{0p}, then the CAS will fail since \code{vic_queue} cannot be equal to \code{0p} because of the check in step 1.
470Therefore in the success case where the \code{CAS} succeeds, the value of the victim's queue pointer must not be \code{0p}.
471As such, the write will never overwrite a value of \code{0p}, hence the invariant is held in the \code{CAS} of step 3.
472The write back to the thief's queue pointer that happens in the failure case of step three and in step 4 hold the invariant since they are the subsequent write to a \code{0p} queue pointer and they are being set by the same thief that set the pointer to \code{0p}.
473
474Given this informal proof of invariance it can be shown that the successful swap is correct.
475Once a thief atomically sets their queue pointer to be \code{0p} in step 2, the invariant guarantees that pointer will not change.
476As such, in the success case step 3 it is known that the value of the victim's queue pointer that was overwritten must be \code{vic_queue} due to the use of \code{CAS}.
477Given that pointers all have unique memory locations, this first write of the successful swap is correct since it can only occur when the pointer has not changed.
478By the invariant the write back in the successful case is correct since no other worker can write to the \code{0p} pointer.
479
480In the failed case the outcome is correct in steps 1 and 2 since no writes have occured so the program state is unchanged.
481In the failed case of step 3 the program state is safely restored to its state it had prior to the \code{0p} write in step 2, thanks to the invariant that makes the write back to the \code{0p} pointer safe.
482
483\subsection{Stealing Guarantees}
484
485% C_TODO insert graphs for each proof
486Given that the stealing operation can potentially fail, it is important to discuss the guarantees provided by the stealing implementation.
487Given a set of $N$ swaps a set of connected directed graphs can be constructed where each vertex is a queue and each edge is a swap directed from a thief queue to a victim queue.
488Since each thief can only steal from one victim at a time, each vertex can only have at most one outgoing edge.
489A corollary that can be drawn from this, is that there are at most $V$ edges in this constructed set of connected directed graphs, where $V$ is the total number of vertices.
490
491\begin{figure}
492\begin{center}
493\input{diagrams/M_to_one_swap.tikz}
494\end{center}
495\caption{Graph of $M$ thieves swapping with one victim.}
496\label{f:M_one_swap}
497\end{figure}
498
499\begin{theorem}
500Given $M$ thieves queues all attempting to swap with one victim queue, and no other swaps occuring that involve these queues, at least one swap is guaranteed to succeed.
501\end{theorem}\label{t:one_vic}
502A graph of the $M$ thieves swapping with one victim discussed in this theorem is presented in Figure~\ref{f:M_one_swap}.
503\\
504First it is important to state that a thief will not attempt to steal from themselves.
505As such, the victim here is not also a thief.
506Stepping through the code in \ref{c:swap}, for all thieves steps 0-1 succeed since the victim is not stealing and will have no queue pointers set to be \code{0p}.
507Similarly for all thieves step 2 will succeed since no one is stealing from any of the thieves.
508In step 3 the first thief to \code{CAS} will win the race and successfully swap the queue pointer.
509Since it is the first one to \code{CAS} and \code{CAS} is atomic, there is no way for the \code{CAS} to fail since no other thief could have written to the victim's queue pointer and the victim did not write to the pointer since they aren't stealing.
510Hence at least one swap is guaranteed to succeed in this case.
511
512\begin{figure}
513\begin{center}
514\input{diagrams/chain_swap.tikz}
515\end{center}
516\caption{Graph of a chain of swaps.}
517\label{f:chain_swap}
518\end{figure}
519
520\begin{theorem}
521Given $M$ > 1, ordered queues pointers all attempting to swap with the queue in front of them in the ordering, except the first queue, and no other swaps occuring that involve these queues, at least one swap is guaranteed to succeed.
522\end{theorem}\label{t:vic_chain}
523A graph of the chain of swaps discussed in this theorem is presented in Figure~\ref{f:chain_swap}.
524\\
525This is a proof by contradiction.
526Assume no swaps occur.
527Then all thieves must have failed at step 1, step 2 or step 3.
528For a given thief $b$ to fail at step 1, thief $b + 1$ must have succeded at step 2 before $b$ executes step 0.
529Hence, not all thieves can fail at step 1.
530Furthermore if a thief $b$ fails at step 1 it logically splits the chain into two subchains $0 <- b$ and $b + 1 <- M - 1$, where $b$ has become solely a victim since its swap has failed and it did not modify any state.
531There must exist at least one chain containing two or more queues after since it is impossible for a split to occur both before and after a thief, since that requires failing at step 1 and succeeding at step 2.
532Hence, without loss of generality, whether thieves succeed or fail at step 1, this proof can proceed inductively.
533
534For a given thief $i$ to fail at step 2, it means that another thief $j$ had to have written to $i$'s queue pointer between $i$'s step 0 and step 2.
535The only way for $j$ to write to $i$'s queue pointer would be if $j$ was stealing from $i$ and had successfully finished step 3.
536If $j$ finished step 3 then the at least one swap was successful.
537Therefore all thieves did not fail at step 2.
538Hence all thieves must successfully complete step 2 and fail at step 3.
539However, since the first worker, thief $0$, is solely a victim and not a thief, it does not change the state of any of its queue pointers.
540Hence, in this case thief $1$ will always succeed in step 3 if all thieves succeed in step 2.
541Thus, by contradiction with the earlier assumption that no swaps occur, at least one swap must succeed.
542
543% \raisebox{.1\height}{}
544\begin{figure}
545\centering
546\begin{tabular}{l|l}
547\subfloat[Cyclic Swap Graph]{\label{f:cyclic_swap}\input{diagrams/cyclic_swap.tikz}} & 
548\subfloat[Acyclic Swap Graph]{\label{f:acyclic_swap}\input{diagrams/acyclic_swap.tikz}} 
549\end{tabular}
550\caption{Illustrations of cyclic and acyclic swap graphs.}
551\end{figure}
552
553\begin{theorem}
554Given a set of $M > 1$ swaps occuring that form a single directed connected graph.
555At least one swap is guaranteed to suceed if and only if the graph does not contain a cycle.
556\end{theorem}\label{t:vic_cycle}
557Representations of cyclic and acylic swap graphs discussed in this theorem are presented in Figures~\ref{f:cyclic_swap} and \ref{f:acyclic_swap}.
558\\
559First the reverse direction is proven.
560If the graph does not contain a cycle, then there must be at least one successful swap.
561Since the graph contains no cycles and is finite in size, then there must be a vertex $A$ with no outgoing edges.
562The graph can then be formulated as a tree with $A$ at the top since each node only has at most one outgoing edge and there are no cycles.
563The forward direction is proven by contradiction in a similar fashion to \ref{t:vic_chain}.
564Assume no swaps occur.
565Similar to \ref{t:vic_chain}, this graph can be inductively split into subgraphs of the same type by failure at step 1, so the proof proceeds without loss of generality.
566Similar to \ref{t:vic_chain} the conclusion is drawn that all thieves must successfully complete step 2 for no swaps to occur, since for step 2 to fail, a different thief has to successfully complete step 3, which would imply a successful swap.
567Hence, the only way forward is to assume all thieves successfully complete step 2.
568Hence for there to be no swaps all thieves must fail step 3.
569However, since $A$ has no outgoing edges, since the graph is connected there must be some $K$ such that $K < M - 1$ thieves are attempting to swap with $A$.
570Since all $K$ thieves have passed step 2, similar to \ref{t:one_vic} the first one of the $K$ thieves to attempt step 3 is guaranteed to succeed.
571Thus, by contradiction with the earlier assumption that no swaps occur, if the graph does not contain a cycle, at least one swap must succeed.
572
573The forward direction is proven by contrapositive.
574If the graph contains a cycle then there exists a situation where no swaps occur.
575This situation is constructed.
576Since all vertices have at most one outgoing edge the cycle must be directed.
577Furthermore, since the graph contains a cycle all vertices in the graph must have exactly one outgoing edge.
578This is shown through construction of an aribtrary cyclic graph.
579The graph contains a directed cycle by definition, so the construction starts with $T$ vertices in a directed cycle.
580Since the graph is connected, and each vertex has at most one outgoing edge, none of the vertices in the cycle have available outgoing edges to accomodate new vertices with no outgoing edges.
581Any vertices added to the graph must have an outgoing edge to connect, leaving the resulting graph with no available outgoing edges.
582Thus, by induction all vertices in the graph must have exactly one outgoing edge.
583Hence all vertices are thief queues.
584Now consider the case where all thieves successfully complete step 0-1, and then they all complete step 2.
585At this point all thieves are attempting to swap with a queue pointer whose value has changed to \code{0p}.
586If all thieves attempt the \code{CAS} before any write backs, then they will all fail.
587Thus, by contrapositive, if the graph contains a cycle then there exists a situation where no swaps occur.
588Hence, at least one swap is guaranteed to suceed if and only if the graph does not contain a cycle.
589
590% C_TODO: go through and use \paragraph to format to make it look nicer
591\subsection{Victim Selection}\label{s:victimSelect}
592In any work stealing algorithm thieves have some heuristic to determine which victim to choose from.
593Choosing this algorithm is difficult and can have implications on performance.
594There is no one selection heuristic that is known to be the best on all workloads.
595Recent work focuses on locality aware scheduling in actor systems\cite{barghi18}\cite{wolke17}.
596However, while locality aware scheduling provides good performance on some workloads, something as simple as randomized selection performs better on other workloads\cite{barghi18}.
597Since locality aware scheduling has been explored recently, this work introduces a heuristic called \textbf{longest victim} and compares it to randomized work stealing.
598The longest victim heuristic maintains a timestamp per worker thread that is updated every time a worker attempts to steal work.
599Thieves then attempt to steal from the thread with the oldest timestamp.
600This means that if two thieves look to steal at the same time, they likely will attempt to steal from the same victim.
601This does increase the chance at contention between thieves, however given that workers have multiple queues under them, often in the tens or hundreds of queues per worker it is rare for two queues to attempt so steal the same queue.
602Furthermore in the case they attempt to steal the same queue at least one of them is guaranteed to successfully steal the queue as shown in Theorem \ref{t:one_vic}.
603Additonally, the longest victim heuristic makes it very improbable that the no swap scenario presented in Theorem \ref{t:vic_cycle} manifests.
604Given the longest victim heuristic, for a cycle to manifest it would require all workers to attempt to steal in a short timeframe.
605This is the only way that more than one thief could choose another thief as a victim, since timestamps are only updated upon attempts to steal.
606In this case, the probability of lack of any successful swaps is a non issue, since it is likely that these steals were not important if all workers are trying to steal.
607
608\section{Safety and Productivity}
609\CFA's actor system comes with a suite of safety and productivity features.
610Most of these features are present in \CFA's debug mode, but are removed when code is compiled in nodebug mode.
611The suit of features include the following.
612
613\begin{itemize}
614\item Static-typed message sends.
615If an actor does not support receiving a given message type, the actor program is rejected at compile time, allowing unsupported messages to never be sent to actors.
616\item Detection of message sends to Finished/Destroyed/Deleted actors.
617All actors have a ticket that assigns them to a respective queue.
618The maximum integer value of the ticket is reserved to indicate that an actor is dead, and subsequent message sends result in an error.
619\item Actors made before the executor can result in undefined behaviour since an executor needs to be created beforehand so it can give out the tickets to actors.
620As such, this is detected and an error is printed.
621\item When an executor is created, the queues are handed out to worker threads in round robin order.
622If there are fewer queues than worker threads, then some workers will spin and never do any work.
623There is no reasonable use case for this behaviour so an error is printed if the number of queues is fewer than the number of worker threads.
624\item A warning is printed when messages are deallocated without being sent.
625Since the \code{Finished} allocation status is unused for messages, it is used internally to detect if a message has been sent.
626Deallocating a message without sending it could indicate to a user that they are touching freed memory later, or it could point out extra allocations that could be removed.
627\end{itemize}
628
629In addition to these features, \CFA's actor system comes with a suite of statistics that can be toggled on and off.
630These statistics have minimal impact on the actor system's performance since they are counted on a per worker thread basis.
631During shutdown of the actor system they are aggregated, ensuring that the only atomic instructions used by the statistics counting happen at shutdown.
632The statistics measured are as follows.
633
634\begin{description}
635\item[\LstBasicStyle{\textbf{Actors Created}}]
636Actors created.
637Includes both actors made by the main and ones made by other actors.
638\item[\LstBasicStyle{\textbf{Messages Sent}}]
639Messages sent and received.
640Includes termination messages send to the worker threads.
641\item[\LstBasicStyle{\textbf{Gulps}}]
642Gulps that occured across the worker threads.
643\item[\LstBasicStyle{\textbf{Average Gulp Size}}]
644Average number of messages in a gulped queue.
645\item[\LstBasicStyle{\textbf{Missed gulps}}]
646Occurences where a worker missed a gulp due to the concurrent queue processing by another worker.
647\item[\LstBasicStyle{\textbf{Steal attempts}}]
648Worker threads attempts to steal work.
649
650\item[\LstBasicStyle{\textbf{Steal failures (no candidates)}}]
651Work stealing failures due to selected victim not having any non empty or non-being-processed queues.
652\item[\LstBasicStyle{\textbf{Steal failures (failed swaps)}}]
653Work stealing failures due to the two stage atomic swap failing.
654\item[\LstBasicStyle{\textbf{Messages stolen}}]
655Aggregate of the number of messages in queues as they were stolen.
656\item[\LstBasicStyle{\textbf{Average steal size}}]
657Average number of messages in a stolen queue.
658\end{description}
659
660These statistics enable a user of \CFA's actor system to make informed choices about how to configure their executor, or how to structure their actor program.
661For example, if there is a lot of messages being stolen relative to the number of messages sent, it could indicate to a user that their workload is heavily imbalanced across worker threads.
662In another example, if the average gulp size is very high, it could indicate that the executor could use more queue sharding.
663
664% C_TODO cite poison pill messages and add languages
665Another productivity feature that is included is a group of poison-pill messages.
666Poison-pill messages are common across actor systems, including Akka and ProtoActor \cite{}.
667Poison-pill messages inform an actor to terminate.
668In \CFA, due to the allocation of actors and lack of garbage collection, there needs to be a suite of poison-pills.
669The messages that \CFA provides are \code{DeleteMsg}, \code{DestroyMsg}, and \code{FinishedMsg}.
670These messages are supported on all actor types via inheritance and when sent to an actor, the actor takes the corresponding allocation action after receiving the message.
671Note that any pending messages to the actor will still be sent.
672It is still the user's responsibility to ensure that an actor does not receive any messages after termination.
673
674\section{Performance}\label{s:actor_perf}
675\CAP{I will update the figures to have the larger font size and different line markers once we start editing this chapter.}
676The performance of \CFA's actor system is tested using a suite of microbenchmarks, and compared with other actor systems.
677Most of the benchmarks are the same as those presented in \ref{}, with a few additions.
678% C_TODO cite actor paper
679At the time of this work the versions of the actor systems are as follows.
680\CFA 1.0, \uC 7.0.0, Akka Typed 2.7.0, CAF 0.18.6, and ProtoActor-Go v0.0.0-20220528090104-f567b547ea07.
681Akka Classic is omitted as Akka Typed is their newest version and seems to be the direction they are headed in.
682The experiments are run on
683\begin{list}{\arabic{enumi}.}{\usecounter{enumi}\topsep=5pt\parsep=5pt\itemsep=0pt}
684\item
685Supermicro SYS--6029U--TR4 Intel Xeon Gold 5220R 24--core socket, hyper-threading $\times$ 2 sockets (48 process\-ing units) 2.2GHz, running Linux v5.8.0--59--generic
686\item
687Supermicro AS--1123US--TR4 AMD EPYC 7662 64--core socket, hyper-threading $\times$ 2 sockets (256 processing units) 2.0 GHz, running Linux v5.8.0--55--generic
688\end{list}
689
690The benchmarks are run on up to 48 cores.
691On the Intel, when going beyond 24 cores there is the choice to either hop sockets or to use hyperthreads.
692Either choice will cause a blip in performance trends, which can be seen in the following performance figures.
693On the Intel the choice was made to hyperthread instead of hopping sockets for experiments with more than 24 cores.
694
695All benchmarks presented are run 5 times and the median is taken.
696Error bars showing the 95\% confidence intervals are drawn on each point on the graphs.
697If the confidence bars are small enough, they may be obscured by the point.
698In this section \uC will be compared to \CFA frequently, as the actor system in \CFA was heavily based off \uC's actor system.
699As such the peformance differences that arise are largely due to the contributions of this work.
700
701\begin{table}[t]
702\centering
703\setlength{\extrarowheight}{2pt}
704\setlength{\tabcolsep}{5pt}
705
706\caption{Static Actor/Message Performance: message send, program memory}
707\label{t:StaticActorMessagePerformance}
708\begin{tabular}{*{5}{r|}r}
709        & \multicolumn{1}{c|}{\CFA (100M)} & \multicolumn{1}{c|}{CAF (10M)} & \multicolumn{1}{c|}{Akka (100M)} & \multicolumn{1}{c|}{\uC (100M)} & \multicolumn{1}{c@{}}{ProtoActor (100M)} \\
710        \hline                                                                                                                                                 
711        AMD             & \input{data/pykeSendStatic} \\
712        \hline                                                                                                                                                 
713        Intel   & \input{data/nasusSendStatic}
714\end{tabular}
715
716\bigskip
717
718\caption{Dynamic Actor/Message Performance: message send, program memory}
719\label{t:DynamicActorMessagePerformance}
720
721\begin{tabular}{*{5}{r|}r}
722        & \multicolumn{1}{c|}{\CFA (20M)} & \multicolumn{1}{c|}{CAF (2M)} & \multicolumn{1}{c|}{Akka (2M)} & \multicolumn{1}{c|}{\uC (20M)} & \multicolumn{1}{c@{}}{ProtoActor (2M)} \\
723        \hline                                                                                                                                                 
724        AMD             & \input{data/pykeSendDynamic} \\
725        \hline                                                                                                                                                 
726        Intel   & \input{data/nasusSendDynamic}
727\end{tabular}
728\end{table}
729
730\subsection{Message Sends}
731Message sending is the key component of actor communication.
732As such latency of a single message send is the fundamental unit of fast-path performance for an actor system.
733The following two microbenchmarks evaluate the average latency for a static actor/message send and a dynamic actor/message send.
734Static and dynamic refer to the allocation of the message and actor.
735In the static send benchmark a message and actor are allocated once and then the message is sent to the same actor repeatedly until it has been sent 100 million (100M) times.
736The average latency per message send is then calculated by dividing the duration by the number of sends.
737This benchmark evaluates the cost of message sends in the actor use case where all actors and messages are allocated ahead of time and do not need to be created dynamically during execution.
738The CAF static send benchmark only sends a message 10M times to avoid extensively long run times.
739
740In the dynamic send benchmark the same experiment is performed, with the change that with each send a new actor and message is allocated.
741This evaluates the cost of message sends in the other common actor pattern where actors and message are created on the fly as the actor program tackles a workload of variable or unknown size.
742Since dynamic sends are more expensive, this benchmark repeats the actor/message creation and send 20M times (\uC, \CFA), or 2M times (Akka, CAF, ProtoActor), to give an appropriate benchmark duration.
743
744The results from the static/dynamic send benchmarks are shown in Figures~\ref{t:StaticActorMessagePerformance} and \ref{t:DynamicActorMessagePerformance} respectively.
745\CFA leads the charts in both benchmarks, largely due to the copy queue removing the majority of the envelope allocations.
746In the static send benchmark all systems except CAF have static send costs that are in the same ballpark, only varying by ~70ns.
747In the dynamic send benchmark all systems experience slower message sends, as expected due to the extra allocations.
748However, Akka and ProtoActor, slow down by a more significant margin than the \uC and \CFA.
749This is likely a result of Akka and ProtoActor's garbage collection, which can suffer from hits in performance for allocation heavy workloads, whereas \uC and \CFA have explicit allocation/deallocation.
750
751\subsection{Work Stealing}
752\CFA's actor system has a work stealing mechanism which uses the longest victim heuristic, introduced in Section~ref{s:victimSelect}.
753In this performance section, \CFA with the longest victim heuristic is compared with other actor systems on the benchmark suite, and is separately compared with vanilla non-stealing \CFA and \CFA with randomized work stealing.
754
755\begin{figure}
756        \centering
757        \subfloat[AMD \CFA Balance-One Benchmark]{
758                \resizebox{0.5\textwidth}{!}{\input{figures/nasusCFABalance-One.pgf}}
759                \label{f:BalanceOneAMD}
760        }
761        \subfloat[Intel \CFA Balance-One Benchmark]{
762                \resizebox{0.5\textwidth}{!}{\input{figures/pykeCFABalance-One.pgf}}
763                \label{f:BalanceOneIntel}
764        }
765        \caption{The balance-one benchmark comparing stealing heuristics (lower is better).}
766\end{figure}
767
768\begin{figure}
769        \centering
770        \subfloat[AMD \CFA Balance-Multi Benchmark]{
771                \resizebox{0.5\textwidth}{!}{\input{figures/nasusCFABalance-Multi.pgf}}
772                \label{f:BalanceMultiAMD}
773        }
774        \subfloat[Intel \CFA Balance-Multi Benchmark]{
775                \resizebox{0.5\textwidth}{!}{\input{figures/pykeCFABalance-Multi.pgf}}
776                \label{f:BalanceMultiIntel}
777        }
778        \caption{The balance-multi benchmark comparing stealing heuristics (lower is better).}
779\end{figure}
780
781There are two benchmarks in which \CFA's work stealing is solely evaluated.
782The main goal of introducing work stealing to \CFA's actor system is to eliminate the pathological unbalanced cases that can present themselves in a system without some form of load balancing.
783The following two microbenchmarks construct two such pathological cases, and compare the work stealing variations of \CFA.
784The balance benchmarks adversarily takes advantage of the round robin assignment of actors to load all actors that will do work on specific cores and create 'dummy' actors that terminate after a single message send on all other cores.
785The workload on the loaded cores is the same as the executor benchmark described in \ref{s:executorPerf}, but with fewer rounds.
786The balance-one benchmark loads all the work on a single core, whereas the balance-multi loads all the work on half the cores (every other core).
787Given this layout, one expects the ideal speedup of work stealing in the balance-one case to be $N / N - 1$ where $N$ is the number of threads.
788In the balance-multi case the ideal speedup is 0.5.
789Note that in the balance-one benchmark the workload is fixed so decreasing runtime is expected.
790In the balance-multi experiment, the workload increases with the number of cores so an increasing or constant runtime is expected.
791
792On both balance microbenchmarks slightly less than ideal speedup compared to the non stealing variation is achieved by both the random and longest victim stealing heuristics.
793On the balance-multi benchmark \ref{f:BalanceMultiAMD},\ref{f:BalanceMultiIntel} the random heuristic outperforms the longest victim.
794This is likely a result of the longest victim heuristic having a higher stealing cost as it needs to maintain timestamps and look at all timestamps before stealing.
795Additionally, a performance cost can be observed when hyperthreading kicks in in Figure~\ref{f:BalanceMultiIntel}.
796
797In the balance-one benchmark on AMD \ref{f:BalanceOneAMD}, the performance bottoms out at 32 cores onwards likely due to the amount of work becoming less than the cost to steal it and move it across cores and cache.
798On Intel \ref{f:BalanceOneIntel}, above 32 cores the performance gets worse for all variants due to hyperthreading.
799Note that the non stealing variation of balance-one will slow down marginally as the cores increase due to having to create more dummy actors on the inactive cores during startup.
800
801\subsection{Executor}\label{s:executorPerf}
802The microbenchmarks in this section are designed to stress the executor.
803The executor is the scheduler of an actor system and is responsible for organizing the interaction of worker threads to service the needs of a workload.
804In the executor benchmark, 40'000 actors are created and assigned a group.
805Each group of actors is a group of 100 actors who send and receive 100 messages from all other actors in their group.
806Each time an actor completes all their sends and receives, they are done a round.
807After all groups have completed 400 rounds the system terminates.
808This microbenchmark is designed to flood the executor with a large number of messages flowing between actors.
809Given there is no work associated with each message, other than sending more messages, the intended bottleneck of this experiment is the executor message send process.
810
811\begin{figure}
812        \centering
813        \subfloat[AMD Executor Benchmark]{
814                \resizebox{0.5\textwidth}{!}{\input{figures/nasusExecutor.pgf}}
815                \label{f:ExecutorAMD}
816        }
817        \subfloat[Intel Executor Benchmark]{
818                \resizebox{0.5\textwidth}{!}{\input{figures/pykeExecutor.pgf}}
819                \label{f:ExecutorIntel}
820        }
821        \caption{The executor benchmark comparing actor systems (lower is better).}
822\end{figure}
823
824The results of the executor benchmark in Figures~\ref{f:ExecutorIntel} and \ref{f:ExecutorAMD} show \CFA with the lowest runtime relative to its peers.
825The difference in runtime between \uC and \CFA is largely due to the usage of the copy queue described in Section~\ref{s:copyQueue}.
826The copy queue both reduces and consolidates allocations, heavily reducing contention on the memory allocator.
827Additionally, due to the static typing in \CFA's actor system, it is able to get rid of expensive dynamic casts that occur in \uC to disciminate messages by type.
828Note that dynamic casts are ususally not very expensive, but relative to the high performance of the rest of the implementation of the \uC actor system, the cost is significant.
829
830\begin{figure}
831        \centering
832        \subfloat[AMD \CFA Executor Benchmark]{
833                \resizebox{0.5\textwidth}{!}{\input{figures/nasusCFAExecutor.pgf}}
834                \label{f:cfaExecutorAMD}
835        }
836        \subfloat[Intel \CFA Executor Benchmark]{
837                \resizebox{0.5\textwidth}{!}{\input{figures/pykeCFAExecutor.pgf}}
838                \label{f:cfaExecutorIntel}
839        }
840        \caption{Executor benchmark comparing \CFA stealing heuristics (lower is better).}
841\end{figure}
842
843When comparing the \CFA stealing heuristics in Figure~\ref{f:cfaExecutorAMD} it can be seen that the random heuristic falls slightly behind the other two, but in Figure~\ref{f:cfaExecutorIntel} the runtime of all heuristics are nearly identical to eachother.
844
845\begin{figure}
846        \centering
847        \subfloat[AMD Repeat Benchmark]{
848                \resizebox{0.5\textwidth}{!}{\input{figures/nasusRepeat.pgf}}
849                \label{f:RepeatAMD}
850        }
851        \subfloat[Intel Repeat Benchmark]{
852                \resizebox{0.5\textwidth}{!}{\input{figures/pykeRepeat.pgf}}
853                \label{f:RepeatIntel}
854        }
855        \caption{The repeat benchmark comparing actor systems (lower is better).}
856\end{figure}
857
858The repeat microbenchmark also evaluates the executor.
859It stresses the executor's ability to withstand contention on queues, as it repeatedly fans out messages from a single client to 100000 servers who then all respond to the client.
860After this scatter and gather repeats 200 times the benchmark terminates.
861The messages from the servers to the client will likely all come in on the same queue, resulting in high contention.
862As such this benchmark will not scale with the number of processors, since more processors will result in higher contention.
863In Figure~\ref{f:RepeatAMD} we can see that \CFA performs well compared to \uC, however by less of a margin than the executor benchmark.
864One factor in this result is that the contention on the queues poses a significant bottleneck.
865As such the gains from using the copy queue are much less apparent.
866
867\begin{figure}
868        \centering
869        \subfloat[AMD \CFA Repeat Benchmark]{
870                \resizebox{0.5\textwidth}{!}{\input{figures/nasusCFARepeat.pgf}}
871                \label{f:cfaRepeatAMD}
872        }
873        \subfloat[Intel \CFA Repeat Benchmark]{
874                \resizebox{0.5\textwidth}{!}{\input{figures/pykeCFARepeat.pgf}}
875                \label{f:cfaRepeatIntel}
876        }
877        \caption{The repeat benchmark comparing \CFA stealing heuristics (lower is better).}
878\end{figure}
879
880In Figure~\ref{f:RepeatIntel} \uC and \CFA are very comparable.
881In comparison with the other systems \uC does well on the repeat benchmark since it does not have work stealing.
882The client of this experiment is long running and maintains a lot of state, as it needs to know the handles of all the servers.
883When stealing the client or its respective queue (in \CFA's inverted model), moving the client incurs a high cost due to cache invalidation.
884As such stealing the client can result in a hit in performance.
885
886This result is shown in Figure~\ref{f:cfaRepeatAMD} and \ref{f:cfaRepeatIntel} where the no-stealing version of \CFA performs better than both stealing variations.
887In particular on the Intel machine in Figure~\ref{f:cfaRepeatIntel}, the cost of stealing is higher, which can be seen in the vertical shift of Akka, CAF and CFA results in Figure~\ref{f:RepeatIntel} (\uC and ProtoActor do not have work stealing).
888The shift for CAF is particularly large, which further supports the hypothesis that CAF's work stealing is particularly eager.
889In both the executor and the repeat benchmark CAF performs poorly.
890It is hypothesized that CAF has an aggressive work stealing algorithm, that eagerly attempts to steal.
891This results in poor performance in benchmarks with small messages containing little work per message.
892On the other hand, in \ref{f:MatrixAMD} CAF performs much better since each message has a large amount of work, and few messages are sent, so the eager work stealing allows for the clean up of loose ends to occur faster.
893This hypothesis stems from experimentation with \CFA.
894CAF uses a randomized work stealing heuristic.
895In \CFA if the system is tuned so that it steals work much more eagerly with a randomized it was able to replicate the results that CAF achieves in the matrix benchmark, but this tuning performed much worse on all other microbenchmarks that we present, since they all perform a small amount of work per message.
896
897\begin{table}[t]
898        \centering
899        \setlength{\extrarowheight}{2pt}
900        \setlength{\tabcolsep}{5pt}
901       
902        \caption{Executor Program Memory High Watermark}
903        \label{t:ExecutorMemory}
904        \begin{tabular}{*{5}{r|}r}
905                & \multicolumn{1}{c|}{\CFA} & \multicolumn{1}{c|}{CAF} & \multicolumn{1}{c|}{Akka} & \multicolumn{1}{c|}{\uC} & \multicolumn{1}{c@{}}{ProtoActor} \\
906                \hline                                                                                                                                                 
907                AMD             & \input{data/pykeExecutorMem} \\
908                \hline                                                                                                                                                 
909                Intel   & \input{data/nasusExecutorMem}
910        \end{tabular}
911\end{table}
912
913Figure~\ref{t:ExecutorMemory} shows the high memory watermark of the actor systems when running the executor benchmark on 48 cores.
914\CFA has a high watermark relative to the other non-garbage collected systems \uC, and CAF.
915This is a result of the copy queue data structure, as it will overallocate storage and not clean up eagerly, whereas the per envelope allocations will always allocate exactly the amount of storage needed.
916
917\subsection{Matrix Multiply}
918The matrix benchmark evaluates the actor systems in a practical application, where actors concurrently multiplies two matrices.
919The majority of the computation in this benchmark involves computing the final matrix, so this benchmark stresses the actor systems' ability to have actors run work, rather than stressing the executor or message sending system.
920
921Given $Z_{m,r} = X_{m,n} \cdot Y_{n,r}$, the matrix multiply is defined as:
922\begin{displaymath}
923X_{i,j} \cdot Y_{j,k} = \left( \sum_{c=1}^{j} X_{row,c}Y_{c,column} \right)_{i,k}
924\end{displaymath}
925
926The benchmark uses input matrices $X$ and $Y$ that are both $3072$ by $3072$ in size.
927An actor is made for each row of $X$ and is passed via message the information needed to calculate a row of the result matrix $Z$.
928
929
930Given that the bottleneck of the benchmark is the computation of the result matrix, it follows that the results in Figures~\ref{f:MatrixAMD} and \ref{f:MatrixIntel} are clustered closer than other experiments.
931In Figure~\ref{f:MatrixAMD} \uC and \CFA have identical performance and in Figure~\ref{f:MatrixIntel} \uC pulls ahead og \CFA after 24 cores likely due to costs associated with work stealing while hyperthreading.
932As mentioned in \ref{s:executorPerf}, it is hypothesized that CAF performs better in this benchmark compared to others due to its eager work stealing implementation.
933In Figures~\ref{f:cfaMatrixAMD} and \ref{f:cfaMatrixIntel} there is little negligible performance difference across \CFA stealing heuristics.
934
935\begin{figure}
936        \centering
937        \subfloat[AMD Matrix Benchmark]{
938                \resizebox{0.5\textwidth}{!}{\input{figures/nasusMatrix.pgf}}
939                \label{f:MatrixAMD}
940        }
941        \subfloat[Intel Matrix Benchmark]{
942                \resizebox{0.5\textwidth}{!}{\input{figures/pykeMatrix.pgf}}
943                \label{f:MatrixIntel}
944        }
945        \caption{The matrix benchmark comparing actor systems (lower is better).}
946\end{figure}
947
948\begin{figure}
949        \centering
950        \subfloat[AMD \CFA Matrix Benchmark]{
951                \resizebox{0.5\textwidth}{!}{\input{figures/nasusCFAMatrix.pgf}}
952                \label{f:cfaMatrixAMD}
953        }
954        \subfloat[Intel \CFA Matrix Benchmark]{
955                \resizebox{0.5\textwidth}{!}{\input{figures/pykeCFAMatrix.pgf}}
956                \label{f:cfaMatrixIntel}
957        }
958        \caption{The matrix benchmark comparing \CFA stealing heuristics (lower is better).}
959\end{figure}
960
961% Local Variables: %
962% tab-width: 4 %
963% End: %
Note: See TracBrowser for help on using the repository browser.