- Timestamp:
- Jun 19, 2023, 1:57:11 PM (2 years ago)
- Branches:
- master
- Children:
- adc73a5
- Parents:
- fa5e1aa5 (diff), 33d4bc8 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the(diff)links above to see all the changes relative to each parent. - Location:
- doc
- Files:
-
- 14 added
- 1 deleted
- 25 edited
-
papers/llheap/Paper.tex (modified) (47 diffs)
-
papers/llheap/figures/AllocatorComponents.fig (modified) (3 diffs)
-
papers/llheap/figures/AllocatorComponents.fig.bak (deleted)
-
theses/colby_parsons_MMAth/Makefile (modified) (3 diffs)
-
theses/colby_parsons_MMAth/benchmarks/actors/cfa/balance.cfa (modified) (3 diffs)
-
theses/colby_parsons_MMAth/benchmarks/actors/cfa/dynamic.cfa (modified) (3 diffs)
-
theses/colby_parsons_MMAth/benchmarks/actors/cfa/executor.cfa (modified) (2 diffs)
-
theses/colby_parsons_MMAth/benchmarks/actors/cfa/matrix.cfa (modified) (2 diffs)
-
theses/colby_parsons_MMAth/benchmarks/actors/cfa/repeat.cfa (modified) (3 diffs)
-
theses/colby_parsons_MMAth/benchmarks/actors/cfa/static.cfa (modified) (3 diffs)
-
theses/colby_parsons_MMAth/benchmarks/actors/plotData.py (modified) (1 diff)
-
theses/colby_parsons_MMAth/benchmarks/channels/plotData.py (modified) (1 diff)
-
theses/colby_parsons_MMAth/benchmarks/mutex_stmt/plotData.py (modified) (1 diff)
-
theses/colby_parsons_MMAth/code/basic_actor_example.cfa (modified) (1 diff)
-
theses/colby_parsons_MMAth/diagrams/gulp.tikz (modified) (2 diffs)
-
theses/colby_parsons_MMAth/diagrams/inverted_actor.tikz (modified) (1 diff)
-
theses/colby_parsons_MMAth/diagrams/standard_actor.tikz (modified) (1 diff)
-
theses/colby_parsons_MMAth/figures/nasus_Contend_2.pgf (added)
-
theses/colby_parsons_MMAth/figures/nasus_Contend_4.pgf (added)
-
theses/colby_parsons_MMAth/figures/nasus_Contend_8.pgf (added)
-
theses/colby_parsons_MMAth/figures/nasus_Future.pgf (added)
-
theses/colby_parsons_MMAth/figures/nasus_Spin_2.pgf (added)
-
theses/colby_parsons_MMAth/figures/nasus_Spin_4.pgf (added)
-
theses/colby_parsons_MMAth/figures/nasus_Spin_8.pgf (added)
-
theses/colby_parsons_MMAth/figures/pyke_Contend_2.pgf (added)
-
theses/colby_parsons_MMAth/figures/pyke_Contend_4.pgf (added)
-
theses/colby_parsons_MMAth/figures/pyke_Contend_8.pgf (added)
-
theses/colby_parsons_MMAth/figures/pyke_Future.pgf (added)
-
theses/colby_parsons_MMAth/figures/pyke_Spin_2.pgf (added)
-
theses/colby_parsons_MMAth/figures/pyke_Spin_4.pgf (added)
-
theses/colby_parsons_MMAth/figures/pyke_Spin_8.pgf (added)
-
theses/colby_parsons_MMAth/glossary.tex (modified) (1 diff)
-
theses/colby_parsons_MMAth/local.bib (modified) (4 diffs)
-
theses/colby_parsons_MMAth/style/style.tex (modified) (1 diff)
-
theses/colby_parsons_MMAth/text/CFA_intro.tex (modified) (1 diff)
-
theses/colby_parsons_MMAth/text/actors.tex (modified) (24 diffs)
-
theses/colby_parsons_MMAth/text/mutex_stmt.tex (modified) (3 diffs)
-
theses/colby_parsons_MMAth/thesis.tex (modified) (2 diffs)
-
user/figures/EHMHierarchy.fig (modified) (1 diff)
-
user/user.tex (modified) (15 diffs)
Legend:
- Unmodified
- Added
- Removed
-
doc/papers/llheap/Paper.tex
rfa5e1aa5 rb7b3e41 252 252 Dynamic code/data memory is managed by the dynamic loader for libraries loaded at runtime, which is complex especially in a multi-threaded program~\cite{Huang06}. 253 253 However, changes to the dynamic code/data space are typically infrequent, many occurring at program startup, and are largely outside of a program's control. 254 Stack memory is managed by the program call/return-mechanism using a simpleLIFO technique, which works well for sequential programs.255 For stackful coroutines and user threads, a new stack is commonly created in dynamic-allocation memory.254 Stack memory is managed by the program call/return-mechanism using a LIFO technique, which works well for sequential programs. 255 For stackful coroutines and user threads, a new stack is commonly created in the dynamic-allocation memory. 256 256 This work focuses solely on management of the dynamic-allocation memory. 257 257 … … 293 293 \begin{enumerate}[leftmargin=*,itemsep=0pt] 294 294 \item 295 Implementation of a new stand-alone concurrent low-latency memory-allocator ($\approx$1,200 lines of code) for C/\CC programs using kernel threads (1:1 threading), and specialized versions of the allocator for the programming languages \uC and \CFAusing user-level threads running on multiple kernel threads (M:N threading).296 297 \item 298 Extend the standard C heap functionality by preserving with each allocation: its request size plus the amount allocated, whether an allocation is zero fill , andallocation alignment.295 Implementation of a new stand-alone concurrent low-latency memory-allocator ($\approx$1,200 lines of code) for C/\CC programs using kernel threads (1:1 threading), and specialized versions of the allocator for the programming languages \uC~\cite{uC++} and \CFA~\cite{Moss18,Delisle21} using user-level threads running on multiple kernel threads (M:N threading). 296 297 \item 298 Extend the standard C heap functionality by preserving with each allocation: its request size plus the amount allocated, whether an allocation is zero fill and/or allocation alignment. 299 299 300 300 \item … … 365 365 366 366 The following discussion is a quick overview of the moving-pieces that affect the design of a memory allocator and its performance. 367 It is assumed that dynamic allocates and deallocates acquire storage for a program variable, referred to asan \newterm{object}, through calls such as @malloc@ and @free@ in C, and @new@ and @delete@ in \CC.367 Dynamic acquires and releases obtain storage for a program variable, called an \newterm{object}, through calls such as @malloc@ and @free@ in C, and @new@ and @delete@ in \CC. 368 368 Space for each allocated object comes from the dynamic-allocation zone. 369 369 … … 378 378 379 379 Figure~\ref{f:AllocatorComponents} shows the two important data components for a memory allocator, management and storage, collectively called the \newterm{heap}. 380 The \newterm{management data} is a data structure located at a known memory address and contains all information necessary to manage the storage data. 381 The management data starts with fixed-sized information in the static-data memory that references components in the dynamic-allocation memory. 380 The \newterm{management data} is a data structure located at a known memory address and contains fixed-sized information in the static-data memory that references components in the dynamic-allocation memory. 382 381 For multi-threaded programs, additional management data may exist in \newterm{thread-local storage} (TLS) for each kernel thread executing the program. 383 382 The \newterm{storage data} is composed of allocated and freed objects, and \newterm{reserved memory}. … … 385 384 \ie only the program knows the location of allocated storage not the memory allocator. 386 385 Freed objects (white) represent memory deallocated by the program, which are linked into one or more lists facilitating easy location of new allocations. 387 Reserved memory (dark grey) is one or more blocks of memory obtained from the operating systembut not yet allocated to the program;388 if there are multiple reserved blocks, they are also chained together , usually internally.386 Reserved memory (dark grey) is one or more blocks of memory obtained from the \newterm{operating system} (OS) but not yet allocated to the program; 387 if there are multiple reserved blocks, they are also chained together. 389 388 390 389 \begin{figure} … … 395 394 \end{figure} 396 395 397 In m ost allocator designs, allocated objects have management data embedded within them.396 In many allocator designs, allocated objects and reserved blocks have management data embedded within them (see also Section~\ref{s:ObjectContainers}). 398 397 Figure~\ref{f:AllocatedObject} shows an allocated object with a header, trailer, and optional spacing around the object. 399 398 The header contains information about the object, \eg size, type, etc. … … 404 403 When padding and spacing are necessary, neither can be used to satisfy a future allocation request while the current allocation exists. 405 404 406 A free object alsocontains management data, \eg size, pointers, etc.405 A free object often contains management data, \eg size, pointers, etc. 407 406 Often the free list is chained internally so it does not consume additional storage, \ie the link fields are placed at known locations in the unused memory blocks. 408 407 For internal chaining, the amount of management data for a free node defines the minimum allocation size, \eg if 16 bytes are needed for a free-list node, allocation requests less than 16 bytes are rounded up. 409 The information in an allocated or freed object is overwritten when it transitions from allocated to freed and vice-versa by new management information and/or program data.408 The information in an allocated or freed object is overwritten when it transitions from allocated to freed and vice-versa by new program data and/or management information. 410 409 411 410 \begin{figure} … … 428 427 \label{s:Fragmentation} 429 428 430 Fragmentation is memory requested from the operating systembut not used by the program;429 Fragmentation is memory requested from the OS but not used by the program; 431 430 hence, allocated objects are not fragmentation. 432 431 Figure~\ref{f:InternalExternalFragmentation} shows fragmentation is divided into two forms: internal or external. … … 443 442 An allocator should strive to keep internal management information to a minimum. 444 443 445 \newterm{External fragmentation} is all memory space reserved from the operating systembut not allocated to the program~\cite{Wilson95,Lim98,Siebert00}, which includes all external management data, freed objects, and reserved memory.444 \newterm{External fragmentation} is all memory space reserved from the OS but not allocated to the program~\cite{Wilson95,Lim98,Siebert00}, which includes all external management data, freed objects, and reserved memory. 446 445 This memory is problematic in two ways: heap blowup and highly fragmented memory. 447 446 \newterm{Heap blowup} occurs when freed memory cannot be reused for future allocations leading to potentially unbounded external fragmentation growth~\cite{Berger00}. 448 Memory can become \newterm{highly fragmented} after multiple allocations and deallocations of objects, resulting in a checkerboard of adjacent allocated and free areas, where the free blocks have become very small.447 Memory can become \newterm{highly fragmented} after multiple allocations and deallocations of objects, resulting in a checkerboard of adjacent allocated and free areas, where the free blocks have become to small to service requests. 449 448 % Figure~\ref{f:MemoryFragmentation} shows an example of how a small block of memory fragments as objects are allocated and deallocated over time. 450 449 Heap blowup can occur due to allocator policies that are too restrictive in reusing freed memory (the allocated size cannot use a larger free block) and/or no coalescing of free storage. … … 452 451 % Memory is highly fragmented when most free blocks are unusable because of their sizes. 453 452 % For example, Figure~\ref{f:Contiguous} and Figure~\ref{f:HighlyFragmented} have the same quantity of external fragmentation, but Figure~\ref{f:HighlyFragmented} is highly fragmented. 454 % If there is a request to allocate a large object, Figure~\ref{f:Contiguous} is more likely to be able to satisfy it with existing free memory, while Figure~\ref{f:HighlyFragmented} likely has to request more memory from the operating system.453 % If there is a request to allocate a large object, Figure~\ref{f:Contiguous} is more likely to be able to satisfy it with existing free memory, while Figure~\ref{f:HighlyFragmented} likely has to request more memory from the OS. 455 454 456 455 % \begin{figure} … … 475 474 The first approach is a \newterm{sequential-fit algorithm} with one list of free objects that is searched for a block large enough to fit a requested object size. 476 475 Different search policies determine the free object selected, \eg the first free object large enough or closest to the requested size. 477 Any storage larger than the request can become spacing after the object or besplit into a smaller free object.476 Any storage larger than the request can become spacing after the object or split into a smaller free object. 478 477 % The cost of the search depends on the shape and quality of the free list, \eg a linear versus a binary-tree free-list, a sorted versus unsorted free-list. 479 478 … … 489 488 490 489 The third approach is \newterm{splitting} and \newterm{coalescing algorithms}. 491 When an object is allocated, if there are no free objects of the requested size, a larger free object may be split into two smaller objects to satisfy the allocation request without obtaining more memory from the operating system.492 For example, in the \newterm{buddy system}, a block of free memory is split into two equal chunks, one of those chunks is again split into two equal chunks, and so on until a block just large enough to fit the requested object is created.493 When an object is deallocated it is coalesced with the objects immediately before and after it in memory, if they are free, turning them into one larger object.490 When an object is allocated, if there are no free objects of the requested size, a larger free object is split into two smaller objects to satisfy the allocation request rather than obtaining more memory from the OS. 491 For example, in the \newterm{buddy system}, a block of free memory is split into equal chunks, one of those chunks is again split, and so on until a minimal block is created that fits the requested object. 492 When an object is deallocated, it is coalesced with the objects immediately before and after it in memory, if they are free, turning them into one larger block. 494 493 Coalescing can be done eagerly at each deallocation or lazily when an allocation cannot be fulfilled. 495 In all cases, coalescing increases allocation latency, hence some allocations can cause unbounded delays during coalescing.494 In all cases, coalescing increases allocation latency, hence some allocations can cause unbounded delays. 496 495 While coalescing does not reduce external fragmentation, the coalesced blocks improve fragmentation quality so future allocations are less likely to cause heap blowup. 497 496 % Splitting and coalescing can be used with other algorithms to avoid highly fragmented memory. … … 501 500 \label{s:Locality} 502 501 503 The principle of locality recognizes that programs tend to reference a small set of data, called a working set, for a certain period of time, where a working set iscomposed of temporal and spatial accesses~\cite{Denning05}.502 The principle of locality recognizes that programs tend to reference a small set of data, called a \newterm{working set}, for a certain period of time, composed of temporal and spatial accesses~\cite{Denning05}. 504 503 % Temporal clustering implies a group of objects are accessed repeatedly within a short time period, while spatial clustering implies a group of objects physically close together (nearby addresses) are accessed repeatedly within a short time period. 505 504 % Temporal locality commonly occurs during an iterative computation with a fixed set of disjoint variables, while spatial locality commonly occurs when traversing an array. 506 Hardware takes advantage of t emporal and spatial localitythrough multiple levels of caching, \ie memory hierarchy.505 Hardware takes advantage of the working set through multiple levels of caching, \ie memory hierarchy. 507 506 % When an object is accessed, the memory physically located around the object is also cached with the expectation that the current and nearby objects will be referenced within a short period of time. 508 For example, entire cache lines are transferred between memory and cache and entire virtual-memory pages are transferred between disk and memory.507 For example, entire cache lines are transferred between cache and memory, and entire virtual-memory pages are transferred between memory and disk. 509 508 % A program exhibiting good locality has better performance due to fewer cache misses and page faults\footnote{With the advent of large RAM memory, paging is becoming less of an issue in modern programming.}. 510 509 … … 532 531 \label{s:MutualExclusion} 533 532 534 \newterm{Mutual exclusion} provides sequential access to the shared management data of the heap.533 \newterm{Mutual exclusion} provides sequential access to the shared-management data of the heap. 535 534 There are two performance issues for mutual exclusion. 536 535 First is the overhead necessary to perform (at least) a hardware atomic operation every time a shared resource is accessed. 537 536 Second is when multiple threads contend for a shared resource simultaneously, and hence, some threads must wait until the resource is released. 538 537 Contention can be reduced in a number of ways: 539 1) Using multiple fine-grained locks versus a single lock , spreadingthe contention across a number of locks.538 1) Using multiple fine-grained locks versus a single lock to spread the contention across a number of locks. 540 539 2) Using trylock and generating new storage if the lock is busy, yielding a classic space versus time tradeoff. 541 540 3) Using one of the many lock-free approaches for reducing contention on basic data-structure operations~\cite{Oyama99}. … … 551 550 a memory allocator can only affect the latter two. 552 551 553 Assume two objects, object$_1$ and object$_2$, share a cache line.554 \newterm{Program-induced false-sharing} occurs when thread$_1$ passes a reference to object$_2$ to thread$_2$, and then threads$_1$ modifies object$_1$ while thread$_2$ modifies object$_2$.552 Specifically, assume two objects, O$_1$ and O$_2$, share a cache line, with threads, T$_1$ and T$_2$. 553 \newterm{Program-induced false-sharing} occurs when T$_1$ passes a reference to O$_2$ to T$_2$, and then T$_1$ modifies O$_1$ while T$_2$ modifies O$_2$. 555 554 % Figure~\ref{f:ProgramInducedFalseSharing} shows when Thread$_1$ passes Object$_2$ to Thread$_2$, a false-sharing situation forms when Thread$_1$ modifies Object$_1$ and Thread$_2$ modifies Object$_2$. 556 555 % Changes to Object$_1$ invalidate CPU$_2$'s cache line, and changes to Object$_2$ invalidate CPU$_1$'s cache line. … … 574 573 % \label{f:FalseSharing} 575 574 % \end{figure} 576 \newterm{Allocator-induced active false-sharing}\label{s:AllocatorInducedActiveFalseSharing} occurs when object$_1$ and object$_2$ are heap allocated and their references are passed to thread$_1$ and thread$_2$, which modify the objects.575 \newterm{Allocator-induced active false-sharing}\label{s:AllocatorInducedActiveFalseSharing} occurs when O$_1$ and O$_2$ are heap allocated and their references are passed to T$_1$ and T$_2$, which modify the objects. 577 576 % For example, in Figure~\ref{f:AllocatorInducedActiveFalseSharing}, each thread allocates an object and loads a cache-line of memory into its associated cache. 578 577 % Again, changes to Object$_1$ invalidate CPU$_2$'s cache line, and changes to Object$_2$ invalidate CPU$_1$'s cache line. … … 580 579 % is another form of allocator-induced false-sharing caused by program-induced false-sharing. 581 580 % When an object in a program-induced false-sharing situation is deallocated, a future allocation of that object may cause passive false-sharing. 582 when thread$_1$ passes object$_2$ to thread$_2$, and thread$_2$ subsequently deallocates object$_2$, and then object$_2$ is reallocated to thread$_2$ while thread$_1$ is still using object$_1$.581 when T$_1$ passes O$_2$ to T$_2$, and T$_2$ subsequently deallocates O$_2$, and then O$_2$ is reallocated to T$_2$ while T$_1$ is still using O$_1$. 583 582 584 583 … … 593 592 \label{s:MultiThreadedMemoryAllocatorFeatures} 594 593 595 The following features are used in the construction of multi-threaded memory-allocators: 596 \begin{enumerate}[itemsep=0pt] 597 \item multiple heaps: with or without a global heap, or with or without heap ownership. 598 \item object containers: with or without ownership, fixed or variable sized, global or local free-lists. 599 \item hybrid private/public heap 600 \item allocation buffer 601 \item lock-free operations 602 \end{enumerate} 594 The following features are used in the construction of multi-threaded memory-allocators: multiple heaps, user-level threading, ownership, object containers, allocation buffer, lock-free operations. 603 595 The first feature, multiple heaps, pertains to different kinds of heaps. 604 596 The second feature, object containers, pertains to the organization of objects within the storage area. … … 606 598 607 599 608 \subs ection{Multiple Heaps}600 \subsubsection{Multiple Heaps} 609 601 \label{s:MultipleHeaps} 610 602 611 603 A multi-threaded allocator has potentially multiple threads and heaps. 612 604 The multiple threads cause complexity, and multiple heaps are a mechanism for dealing with the complexity. 613 The spectrum ranges from multiple threads using a single heap, denoted as T:1 (see Figure~\ref{f:SingleHeap}), to multiple threads sharing multiple heaps, denoted as T:H (see Figure~\ref{f:SharedHeaps}), to one thread per heap, denoted as 1:1 (see Figure~\ref{f:PerThreadHeap}), which is almost back to a single-threaded allocator.605 The spectrum ranges from multiple threads using a single heap, denoted as T:1, to multiple threads sharing multiple heaps, denoted as T:H, to one thread per heap, denoted as 1:1, which is almost back to a single-threaded allocator. 614 606 615 607 \begin{figure} … … 635 627 \end{figure} 636 628 637 \paragraph{T:1 model } where all threads allocate and deallocate objects from one heap.638 Memory is obtained from the freed objects, or reserved memory in the heap, or from the operating system (OS);639 the heap may also return freed memory to the operating system.629 \paragraph{T:1 model (see Figure~\ref{f:SingleHeap})} where all threads allocate and deallocate objects from one heap. 630 Memory is obtained from the freed objects, or reserved memory in the heap, or from the OS; 631 the heap may also return freed memory to the OS. 640 632 The arrows indicate the direction memory conceptually moves for each kind of operation: allocation moves memory along the path from the heap/operating-system to the user application, while deallocation moves memory along the path from the application back to the heap/operating-system. 641 633 To safely handle concurrency, a single lock may be used for all heap operations or fine-grained locking for different operations. 642 634 Regardless, a single heap may be a significant source of contention for programs with a large amount of memory allocation. 643 635 644 \paragraph{T:H model } where each thread allocates storage from several heaps depending on certain criteria, with the goal of reducing contention by spreading allocations/deallocations across the heaps.636 \paragraph{T:H model (see Figure~\ref{f:SharedHeaps})} where each thread allocates storage from several heaps depending on certain criteria, with the goal of reducing contention by spreading allocations/deallocations across the heaps. 645 637 The decision on when to create a new heap and which heap a thread allocates from depends on the allocator design. 646 638 To determine which heap to access, each thread must point to its associated heap in some way. … … 673 665 An alternative implementation is for all heaps to share one reserved memory, which requires a separate lock for the reserved storage to ensure mutual exclusion when acquiring new memory. 674 666 Because multiple threads can allocate/free/reallocate adjacent storage, all forms of false sharing may occur. 675 Other storage-management options are to use @mmap@ to set aside (large) areas of virtual memory for each heap and suballocate each heap's storage within that area, pushing part of the storage management complexity back to the operating system.667 Other storage-management options are to use @mmap@ to set aside (large) areas of virtual memory for each heap and suballocate each heap's storage within that area, pushing part of the storage management complexity back to the OS. 676 668 677 669 % \begin{figure} … … 684 676 Multiple heaps increase external fragmentation as the ratio of heaps to threads increases, which can lead to heap blowup. 685 677 The external fragmentation experienced by a program with a single heap is now multiplied by the number of heaps, since each heap manages its own free storage and allocates its own reserved memory. 686 Additionally, objects freed by one heap cannot be reused by other threads without increasing the cost of the memory operations, except indirectly by returning free memory to the operating system, which can be expensive.687 Depending on how the operating system provides dynamic storage to an application, returning storagemay be difficult or impossible, \eg the contiguous @sbrk@ area in Unix.688 In the worst case, a program in which objects are allocated from one heap but deallocated to another heap means these freed objects are never reused.678 Additionally, objects freed by one heap cannot be reused by other threads without increasing the cost of the memory operations, except indirectly by returning free memory to the OS (see Section~\ref{s:Ownership}). 679 Returning storage to the OS may be difficult or impossible, \eg the contiguous @sbrk@ area in Unix. 680 % In the worst case, a program in which objects are allocated from one heap but deallocated to another heap means these freed objects are never reused. 689 681 690 682 Adding a \newterm{global heap} (G) attempts to reduce the cost of obtaining/returning memory among heaps (sharing) by buffering storage within the application address-space. 691 Now, each heap obtains and returns storage to/from the global heap rather than the operating system.683 Now, each heap obtains and returns storage to/from the global heap rather than the OS. 692 684 Storage is obtained from the global heap only when a heap allocation cannot be fulfilled, and returned to the global heap when a heap's free memory exceeds some threshold. 693 Similarly, the global heap buffers this memory, obtaining and returning storage to/from the operating systemas necessary.685 Similarly, the global heap buffers this memory, obtaining and returning storage to/from the OS as necessary. 694 686 The global heap does not have its own thread and makes no internal allocation requests; 695 687 instead, it uses the application thread, which called one of the multiple heaps and then the global heap, to perform operations. 696 688 Hence, the worst-case cost of a memory operation includes all these steps. 697 With respect to heap blowup, the global heap provides an indirect mechanism to move free memory among heaps, which usually has a much lower cost than interacting with the operating system to achieve the same goal and is independent of the mechanism used by the operating system to present dynamic memory to an address space. 698 689 With respect to heap blowup, the global heap provides an indirect mechanism to move free memory among heaps, which usually has a much lower cost than interacting with the OS to achieve the same goal and is independent of the mechanism used by the OS to present dynamic memory to an address space. 699 690 However, since any thread may indirectly perform a memory operation on the global heap, it is a shared resource that requires locking. 700 691 A single lock can be used to protect the global heap or fine-grained locking can be used to reduce contention. 701 692 In general, the cost is minimal since the majority of memory operations are completed without the use of the global heap. 702 693 703 704 \paragraph{1:1 model (thread heaps)} where each thread has its own heap eliminating most contention and locking because threads seldom access another thread's heap (see ownership in Section~\ref{s:Ownership}). 694 \paragraph{1:1 model (see Figure~\ref{f:PerThreadHeap})} where each thread has its own heap eliminating most contention and locking because threads seldom access another thread's heap (see Section~\ref{s:Ownership}). 705 695 An additional benefit of thread heaps is improved locality due to better memory layout. 706 696 As each thread only allocates from its heap, all objects are consolidated in the storage area for that heap, better utilizing each CPUs cache and accessing fewer pages. … … 708 698 Thread heaps can also eliminate allocator-induced active false-sharing, if memory is acquired so it does not overlap at crucial boundaries with memory for another thread's heap. 709 699 For example, assume page boundaries coincide with cache line boundaries, if a thread heap always acquires pages of memory then no two threads share a page or cache line unless pointers are passed among them. 710 Hence, allocator-induced active false-sharing cannot occur because the memory for thread heaps never overlaps.700 % Hence, allocator-induced active false-sharing cannot occur because the memory for thread heaps never overlaps. 711 701 712 702 When a thread terminates, there are two options for handling its thread heap. … … 720 710 721 711 It is possible to use any of the heap models with user-level (M:N) threading. 722 However, an important goal of user-level threading is for fast operations (creation/termination/context-switching) by not interacting with the operating system, which allows the ability to create large numbers of high-performance interacting threads ($>$ 10,000).712 However, an important goal of user-level threading is for fast operations (creation/termination/context-switching) by not interacting with the OS, which allows the ability to create large numbers of high-performance interacting threads ($>$ 10,000). 723 713 It is difficult to retain this goal, if the user-threading model is directly involved with the heap model. 724 714 Figure~\ref{f:UserLevelKernelHeaps} shows that virtually all user-level threading systems use whatever kernel-level heap-model is provided by the language runtime. … … 732 722 \end{figure} 733 723 734 Adopting this modelresults in a subtle problem with shared heaps.735 With kernel threading, an operation that isstarted by a kernel thread is always completed by that thread.736 For example, if a kernel thread starts an allocation/deallocation on a shared heap, it always completes that operation with that heap even if preempted, \ie any locking correctness associated with the shared heap is preserved across preemption.724 Adopting user threading results in a subtle problem with shared heaps. 725 With kernel threading, an operation started by a kernel thread is always completed by that thread. 726 For example, if a kernel thread starts an allocation/deallocation on a shared heap, it always completes that operation with that heap, even if preempted, \ie any locking correctness associated with the shared heap is preserved across preemption. 737 727 However, this correctness property is not preserved for user-level threading. 738 728 A user thread can start an allocation/deallocation on one kernel thread, be preempted (time slice), and continue running on a different kernel thread to complete the operation~\cite{Dice02}. 739 729 When the user thread continues on the new kernel thread, it may have pointers into the previous kernel-thread's heap and hold locks associated with it. 740 730 To get the same kernel-thread safety, time slicing must be disabled/\-enabled around these operations, so the user thread cannot jump to another kernel thread. 741 However, eagerly disabling/enabling time-slicing on the allocation/deallocation fast path is expensive, because preemption does not happen that frequently.731 However, eagerly disabling/enabling time-slicing on the allocation/deallocation fast path is expensive, because preemption is infrequent (milliseconds). 742 732 Instead, techniques exist to lazily detect this case in the interrupt handler, abort the preemption, and return to the operation so it can complete atomically. 743 Occasional ly ignoring a preemption should be benign, but a persistent lack of preemption can result in both short and long termstarvation;744 techniques like roll forward can be used to force an eventual preemption.733 Occasional ignoring of a preemption should be benign, but a persistent lack of preemption can result in starvation; 734 techniques like rolling forward the preemption to the next context switch can be used. 745 735 746 736 … … 800 790 % For example, in Figure~\ref{f:AllocatorInducedPassiveFalseSharing}, Object$_2$ may be deallocated to Thread$_2$'s heap initially. 801 791 % If Thread$_2$ reallocates Object$_2$ before it is returned to its owner heap, then passive false-sharing may occur. 792 793 For thread heaps with ownership, it is possible to combine these approaches into a hybrid approach with both private and public heaps.% (see~Figure~\ref{f:HybridPrivatePublicHeap}). 794 The main goal of the hybrid approach is to eliminate locking on thread-local allocation/deallocation, while providing ownership to prevent heap blowup. 795 In the hybrid approach, a thread first allocates from its private heap and second from its public heap if no free memory exists in the private heap. 796 Similarly, a thread first deallocates an object to its private heap, and second to the public heap. 797 Both private and public heaps can allocate/deallocate to/from the global heap if there is no free memory or excess free memory, although an implementation may choose to funnel all interaction with the global heap through one of the heaps. 798 % Note, deallocation from the private to the public (dashed line) is unlikely because there is no obvious advantages unless the public heap provides the only interface to the global heap. 799 Finally, when a thread frees an object it does not own, the object is either freed immediately to its owner's public heap or put in the freeing thread's private heap for delayed ownership, which does allows the freeing thread to temporarily reuse an object before returning it to its owner or batch objects for an owner heap into a single return. 800 801 % \begin{figure} 802 % \centering 803 % \input{PrivatePublicHeaps.pstex_t} 804 % \caption{Hybrid Private/Public Heap for Per-thread Heaps} 805 % \label{f:HybridPrivatePublicHeap} 806 % \vspace{10pt} 807 % \input{RemoteFreeList.pstex_t} 808 % \caption{Remote Free-List} 809 % \label{f:RemoteFreeList} 810 % \end{figure} 811 812 % As mentioned, an implementation may have only one heap interact with the global heap, so the other heap can be simplified. 813 % For example, if only the private heap interacts with the global heap, the public heap can be reduced to a lock-protected free-list of objects deallocated by other threads due to ownership, called a \newterm{remote free-list}. 814 % To avoid heap blowup, the private heap allocates from the remote free-list when it reaches some threshold or it has no free storage. 815 % Since the remote free-list is occasionally cleared during an allocation, this adds to that cost. 816 % Clearing the remote free-list is $O(1)$ if the list can simply be added to the end of the private-heap's free-list, or $O(N)$ if some action must be performed for each freed object. 817 818 % If only the public heap interacts with other threads and the global heap, the private heap can handle thread-local allocations and deallocations without locking. 819 % In this scenario, the private heap must deallocate storage after reaching a certain threshold to the public heap (and then eventually to the global heap from the public heap) or heap blowup can occur. 820 % If the public heap does the major management, the private heap can be simplified to provide high-performance thread-local allocations and deallocations. 821 822 % The main disadvantage of each thread having both a private and public heap is the complexity of managing two heaps and their interactions in an allocator. 823 % Interestingly, heap implementations often focus on either a private or public heap, giving the impression a single versus a hybrid approach is being used. 824 % In many case, the hybrid approach is actually being used, but the simpler heap is just folded into the complex heap, even though the operations logically belong in separate heaps. 825 % For example, a remote free-list is actually a simple public-heap, but may be implemented as an integral component of the complex private-heap in an allocator, masking the presence of a hybrid approach. 802 826 803 827 … … 817 841 818 842 819 \subs ection{Object Containers}843 \subsubsection{Object Containers} 820 844 \label{s:ObjectContainers} 821 845 … … 827 851 \eg an object is accessed by the program after it is allocated, while the header is accessed by the allocator after it is free. 828 852 829 The alternative factors common header data to a separate location in memory and organizes associated free storage into blocks called \newterm{object containers} (\newterm{superblocks} in~\cite{Berger00}), as in Figure~\ref{f:ObjectContainer}.853 An alternative approach factors common header data to a separate location in memory and organizes associated free storage into blocks called \newterm{object containers} (\newterm{superblocks}~\cite{Berger00}), as in Figure~\ref{f:ObjectContainer}. 830 854 The header for the container holds information necessary for all objects in the container; 831 855 a trailer may also be used at the end of the container. … … 862 886 863 887 864 \ subsubsection{Container Ownership}888 \paragraph{Container Ownership} 865 889 \label{s:ContainerOwnership} 866 890 … … 894 918 895 919 Additional restrictions may be applied to the movement of containers to prevent active false-sharing. 896 For example, if a container changes ownership through the global heap, then when a thread allocates an object from the newly acquired container itis actively false-sharing even though no objects are passed among threads.920 For example, if a container changes ownership through the global heap, then a thread allocating from the newly acquired container is actively false-sharing even though no objects are passed among threads. 897 921 Note, once the thread frees the object, no more false sharing can occur until the container changes ownership again. 898 922 To prevent this form of false sharing, container movement may be restricted to when all objects in the container are free. 899 One implementation approach that increases the freedom to return a free container to the operating system involves allocating containers using a call like @mmap@, which allows memory at an arbitrary address to be returned versus only storage at the end of the contiguous @sbrk@ area, again pushing storage management complexity back to the operating system.923 One implementation approach that increases the freedom to return a free container to the OS involves allocating containers using a call like @mmap@, which allows memory at an arbitrary address to be returned versus only storage at the end of the contiguous @sbrk@ area, again pushing storage management complexity back to the OS. 900 924 901 925 % \begin{figure} … … 930 954 931 955 932 \ subsubsection{Container Size}956 \paragraph{Container Size} 933 957 \label{s:ContainerSize} 934 958 … … 941 965 However, with more objects in a container, there may be more objects that are unallocated, increasing external fragmentation. 942 966 With smaller containers, not only are there more containers, but a second new problem arises where objects are larger than the container. 943 In general, large objects, \eg greater than 64\,KB, are allocated directly from the operating system and are returned immediately to the operating systemto reduce long-term external fragmentation.967 In general, large objects, \eg greater than 64\,KB, are allocated directly from the OS and are returned immediately to the OS to reduce long-term external fragmentation. 944 968 If the container size is small, \eg 1\,KB, then a 1.5\,KB object is treated as a large object, which is likely to be inappropriate. 945 969 Ideally, it is best to use smaller containers for smaller objects, and larger containers for medium objects, which leads to the issue of locating the container header. … … 970 994 971 995 972 \ subsubsection{Container Free-Lists}996 \paragraph{Container Free-Lists} 973 997 \label{s:containersfreelists} 974 998 … … 1005 1029 1006 1030 1007 \subsubsection{Hybrid Private/Public Heap} 1008 \label{s:HybridPrivatePublicHeap} 1009 1010 Section~\ref{s:Ownership} discusses advantages and disadvantages of public heaps (T:H model and with ownership) and private heaps (thread heaps with ownership). 1011 For thread heaps with ownership, it is possible to combine these approaches into a hybrid approach with both private and public heaps (see~Figure~\ref{f:HybridPrivatePublicHeap}). 1012 The main goal of the hybrid approach is to eliminate locking on thread-local allocation/deallocation, while providing ownership to prevent heap blowup. 1013 In the hybrid approach, a thread first allocates from its private heap and second from its public heap if no free memory exists in the private heap. 1014 Similarly, a thread first deallocates an object to its private heap, and second to the public heap. 1015 Both private and public heaps can allocate/deallocate to/from the global heap if there is no free memory or excess free memory, although an implementation may choose to funnel all interaction with the global heap through one of the heaps. 1016 Note, deallocation from the private to the public (dashed line) is unlikely because there is no obvious advantages unless the public heap provides the only interface to the global heap. 1017 Finally, when a thread frees an object it does not own, the object is either freed immediately to its owner's public heap or put in the freeing thread's private heap for delayed ownership, which allows the freeing thread to temporarily reuse an object before returning it to its owner or batch objects for an owner heap into a single return. 1018 1019 \begin{figure} 1020 \centering 1021 \input{PrivatePublicHeaps.pstex_t} 1022 \caption{Hybrid Private/Public Heap for Per-thread Heaps} 1023 \label{f:HybridPrivatePublicHeap} 1024 % \vspace{10pt} 1025 % \input{RemoteFreeList.pstex_t} 1026 % \caption{Remote Free-List} 1027 % \label{f:RemoteFreeList} 1028 \end{figure} 1029 1030 As mentioned, an implementation may have only one heap interact with the global heap, so the other heap can be simplified. 1031 For example, if only the private heap interacts with the global heap, the public heap can be reduced to a lock-protected free-list of objects deallocated by other threads due to ownership, called a \newterm{remote free-list}. 1032 To avoid heap blowup, the private heap allocates from the remote free-list when it reaches some threshold or it has no free storage. 1033 Since the remote free-list is occasionally cleared during an allocation, this adds to that cost. 1034 Clearing the remote free-list is $O(1)$ if the list can simply be added to the end of the private-heap's free-list, or $O(N)$ if some action must be performed for each freed object. 1035 1036 If only the public heap interacts with other threads and the global heap, the private heap can handle thread-local allocations and deallocations without locking. 1037 In this scenario, the private heap must deallocate storage after reaching a certain threshold to the public heap (and then eventually to the global heap from the public heap) or heap blowup can occur. 1038 If the public heap does the major management, the private heap can be simplified to provide high-performance thread-local allocations and deallocations. 1039 1040 The main disadvantage of each thread having both a private and public heap is the complexity of managing two heaps and their interactions in an allocator. 1041 Interestingly, heap implementations often focus on either a private or public heap, giving the impression a single versus a hybrid approach is being used. 1042 In many case, the hybrid approach is actually being used, but the simpler heap is just folded into the complex heap, even though the operations logically belong in separate heaps. 1043 For example, a remote free-list is actually a simple public-heap, but may be implemented as an integral component of the complex private-heap in an allocator, masking the presence of a hybrid approach. 1044 1045 1046 \subsection{Allocation Buffer} 1031 \subsubsection{Allocation Buffer} 1047 1032 \label{s:AllocationBuffer} 1048 1033 1049 1034 An allocation buffer is reserved memory (see Section~\ref{s:AllocatorComponents}) not yet allocated to the program, and is used for allocating objects when the free list is empty. 1050 1035 That is, rather than requesting new storage for a single object, an entire buffer is requested from which multiple objects are allocated later. 1051 Any heap may use an allocation buffer, resulting in allocation from the buffer before requesting objects (containers) from the global heap or operating system, respectively.1036 Any heap may use an allocation buffer, resulting in allocation from the buffer before requesting objects (containers) from the global heap or OS, respectively. 1052 1037 The allocation buffer reduces contention and the number of global/operating-system calls. 1053 1038 For coalescing, a buffer is split into smaller objects by allocations, and recomposed into larger buffer areas during deallocations. … … 1062 1047 1063 1048 Allocation buffers may increase external fragmentation, since some memory in the allocation buffer may never be allocated. 1064 A smaller allocation buffer reduces the amount of external fragmentation, but increases the number of calls to the global heap or operating system.1049 A smaller allocation buffer reduces the amount of external fragmentation, but increases the number of calls to the global heap or OS. 1065 1050 The allocation buffer also slightly increases internal fragmentation, since a pointer is necessary to locate the next free object in the buffer. 1066 1051 … … 1068 1053 For example, when a container is created, rather than placing all objects within the container on the free list, the objects form an allocation buffer and are allocated from the buffer as allocation requests are made. 1069 1054 This lazy method of constructing objects is beneficial in terms of paging and caching. 1070 For example, although an entire container, possibly spanning several pages, is allocated from the operating system, only a small part of the container is used in the working set of the allocator, reducing the number of pages and cache lines that are brought into higher levels of cache.1071 1072 1073 \subs ection{Lock-Free Operations}1055 For example, although an entire container, possibly spanning several pages, is allocated from the OS, only a small part of the container is used in the working set of the allocator, reducing the number of pages and cache lines that are brought into higher levels of cache. 1056 1057 1058 \subsubsection{Lock-Free Operations} 1074 1059 \label{s:LockFreeOperations} 1075 1060 … … 1194 1179 % A sequence of code that is guaranteed to run to completion before being invoked to accept another input is called serially-reusable code.~\cite{SeriallyReusable}\label{p:SeriallyReusable} 1195 1180 % \end{quote} 1196 % If a KT is preempted during an allocation operation, the operating systemcan schedule another KT on the same CPU, which can begin an allocation operation before the previous operation associated with this CPU has completed, invalidating heap correctness.1181 % If a KT is preempted during an allocation operation, the OS can schedule another KT on the same CPU, which can begin an allocation operation before the previous operation associated with this CPU has completed, invalidating heap correctness. 1197 1182 % Note, the serially-reusable problem can occur in sequential programs with preemption, if the signal handler calls the preempted function, unless the function is serially reusable. 1198 % Essentially, the serially-reusable problem is a race condition on an unprotected critical subsection, where the operating systemis providing the second thread via the signal handler.1183 % Essentially, the serially-reusable problem is a race condition on an unprotected critical subsection, where the OS is providing the second thread via the signal handler. 1199 1184 % 1200 1185 % Library @librseq@~\cite{librseq} was used to perform a fast determination of the CPU and to ensure all memory operations complete on one CPU using @librseq@'s restartable sequences, which restart the critical subsection after undoing its writes, if the critical subsection is preempted. … … 1256 1241 A sequence of code that is guaranteed to run to completion before being invoked to accept another input is called serially-reusable code.~\cite{SeriallyReusable}\label{p:SeriallyReusable} 1257 1242 \end{quote} 1258 If a KT is preempted during an allocation operation, the operating systemcan schedule another KT on the same CPU, which can begin an allocation operation before the previous operation associated with this CPU has completed, invalidating heap correctness.1243 If a KT is preempted during an allocation operation, the OS can schedule another KT on the same CPU, which can begin an allocation operation before the previous operation associated with this CPU has completed, invalidating heap correctness. 1259 1244 Note, the serially-reusable problem can occur in sequential programs with preemption, if the signal handler calls the preempted function, unless the function is serially reusable. 1260 Essentially, the serially-reusable problem is a race condition on an unprotected critical subsection, where the operating systemis providing the second thread via the signal handler.1245 Essentially, the serially-reusable problem is a race condition on an unprotected critical subsection, where the OS is providing the second thread via the signal handler. 1261 1246 1262 1247 Library @librseq@~\cite{librseq} was used to perform a fast determination of the CPU and to ensure all memory operations complete on one CPU using @librseq@'s restartable sequences, which restart the critical subsection after undoing its writes, if the critical subsection is preempted. … … 1273 1258 For the T:H=CPU and 1:1 models, locking is eliminated along the allocation fastpath. 1274 1259 However, T:H=CPU has poor operating-system support to determine the CPU id (heap id) and prevent the serially-reusable problem for KTs. 1275 More operating systemsupport is required to make this model viable, but there is still the serially-reusable problem with user-level threading.1260 More OS support is required to make this model viable, but there is still the serially-reusable problem with user-level threading. 1276 1261 So the 1:1 model had no atomic actions along the fastpath and no special operating-system support requirements. 1277 1262 The 1:1 model still has the serially-reusable problem with user-level threading, which is addressed in Section~\ref{s:UserlevelThreadingSupport}, and the greatest potential for heap blowup for certain allocation patterns. … … 1308 1293 A primary goal of llheap is low latency, hence the name low-latency heap (llheap). 1309 1294 Two forms of latency are internal and external. 1310 Internal latency is the time to perform an allocation, while external latency is time to obtain/return storage from/to the operating system.1295 Internal latency is the time to perform an allocation, while external latency is time to obtain/return storage from/to the OS. 1311 1296 Ideally latency is $O(1)$ with a small constant. 1312 1297 … … 1314 1299 The mitigating factor is that most programs have well behaved allocation patterns, where the majority of allocation operations can be $O(1)$, and heap blowup does not occur without coalescing (although the allocation footprint may be slightly larger). 1315 1300 1316 To obtain $O(1)$ external latency means obtaining one large storage area from the operating systemand subdividing it across all program allocations, which requires a good guess at the program storage high-watermark and potential large external fragmentation.1301 To obtain $O(1)$ external latency means obtaining one large storage area from the OS and subdividing it across all program allocations, which requires a good guess at the program storage high-watermark and potential large external fragmentation. 1317 1302 Excluding real-time operating-systems, operating-system operations are unbounded, and hence some external latency is unavoidable. 1318 1303 The mitigating factor is that operating-system calls can often be reduced if a programmer has a sense of the storage high-watermark and the allocator is capable of using this information (see @malloc_expansion@ \pageref{p:malloc_expansion}). … … 1329 1314 headers per allocation versus containers, 1330 1315 no coalescing to minimize latency, 1331 global heap memory (pool) obtained from the operating systemusing @mmap@ to create and reuse heaps needed by threads,1316 global heap memory (pool) obtained from the OS using @mmap@ to create and reuse heaps needed by threads, 1332 1317 local reserved memory (pool) per heap obtained from global pool, 1333 global reserved memory (pool) obtained from the operating systemusing @sbrk@ call,1318 global reserved memory (pool) obtained from the OS using @sbrk@ call, 1334 1319 optional fast-lookup table for converting allocation requests into bucket sizes, 1335 1320 optional statistic-counters table for accumulating counts of allocation operations. … … 1358 1343 Each heap uses segregated free-buckets that have free objects distributed across 91 different sizes from 16 to 4M. 1359 1344 All objects in a bucket are of the same size. 1360 The number of buckets used is determined dynamically depending on the crossover point from @sbrk@ to @mmap@ allocation using @mallopt( M_MMAP_THRESHOLD )@, \ie small objects managed by the program and large objects managed by the operating system.1345 The number of buckets used is determined dynamically depending on the crossover point from @sbrk@ to @mmap@ allocation using @mallopt( M_MMAP_THRESHOLD )@, \ie small objects managed by the program and large objects managed by the OS. 1361 1346 Each free bucket of a specific size has two lists. 1362 1347 1) A free stack used solely by the KT heap-owner, so push/pop operations do not require locking. … … 1367 1352 Algorithm~\ref{alg:heapObjectAlloc} shows the allocation outline for an object of size $S$. 1368 1353 First, the allocation is divided into small (@sbrk@) or large (@mmap@). 1369 For large allocations, the storage is mapped directly from the operating system.1354 For large allocations, the storage is mapped directly from the OS. 1370 1355 For small allocations, $S$ is quantized into a bucket size. 1371 1356 Quantizing is performed using a binary search over the ordered bucket array. … … 1378 1363 heap's local pool, 1379 1364 global pool, 1380 operating system(@sbrk@).1365 OS (@sbrk@). 1381 1366 1382 1367 \begin{algorithm} … … 1443 1428 Algorithm~\ref{alg:heapObjectFreeOwn} shows the de-allocation (free) outline for an object at address $A$ with ownership. 1444 1429 First, the address is divided into small (@sbrk@) or large (@mmap@). 1445 For large allocations, the storage is unmapped back to the operating system.1430 For large allocations, the storage is unmapped back to the OS. 1446 1431 For small allocations, the bucket associated with the request size is retrieved. 1447 1432 If the bucket is local to the thread, the allocation is pushed onto the thread's associated bucket. … … 3044 3029 3045 3030 \textsf{pt3} is the only memory allocator where the total dynamic memory goes down in the second half of the program lifetime when the memory is freed by the benchmark program. 3046 It makes pt3 the only memory allocator that gives memory back to the operating systemas it is freed by the program.3031 It makes pt3 the only memory allocator that gives memory back to the OS as it is freed by the program. 3047 3032 3048 3033 % FOR 1 THREAD -
doc/papers/llheap/figures/AllocatorComponents.fig
rfa5e1aa5 rb7b3e41 8 8 -2 9 9 1200 2 10 6 1275 2025 2700 262511 10 6 2400 2025 2700 2625 12 11 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 … … 14 13 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 15 14 2700 2025 2700 2325 2400 2325 2400 2025 2700 2025 16 -617 4 2 0 50 -1 2 11 0.0000 2 165 1005 2325 2400 Management\00118 15 -6 19 16 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 … … 61 58 2 2 0 1 0 7 60 -1 13 0.000 0 0 -1 0 0 5 62 59 3300 2700 6300 2700 6300 3000 3300 3000 3300 2700 63 4 0 0 50 -1 2 11 0.0000 2 165 585 3300 1725 Storage\00160 4 0 0 50 -1 2 11 0.0000 2 165 1005 3300 1725 Storage Data\001 64 61 4 2 0 50 -1 0 11 0.0000 2 165 810 3000 1875 free objects\001 65 62 4 2 0 50 -1 0 11 0.0000 2 135 1140 3000 2850 reserve memory\001 66 63 4 1 0 50 -1 0 11 0.0000 2 120 795 2325 1500 Static Zone\001 67 64 4 1 0 50 -1 0 11 0.0000 2 165 1845 4800 1500 Dynamic-Allocation Zone\001 65 4 2 0 50 -1 2 11 0.0000 2 165 1005 2325 2325 Management\001 66 4 2 0 50 -1 2 11 0.0000 2 135 375 2325 2525 Data\001 -
doc/theses/colby_parsons_MMAth/Makefile
rfa5e1aa5 rb7b3e41 50 50 figures/nasus_Channel_Contention \ 51 51 figures/pyke_Channel_Contention \ 52 figures/pyke_Future \ 53 figures/nasus_Future \ 54 figures/pyke_Contend_2 \ 55 figures/pyke_Contend_4 \ 56 figures/pyke_Contend_8 \ 57 figures/pyke_Spin_2 \ 58 figures/pyke_Spin_4 \ 59 figures/pyke_Spin_8 \ 60 figures/nasus_Contend_2 \ 61 figures/nasus_Contend_4 \ 62 figures/nasus_Contend_8 \ 63 figures/nasus_Spin_2 \ 64 figures/nasus_Spin_4 \ 65 figures/nasus_Spin_8 \ 52 66 } 53 67 … … 98 112 99 113 ${BASE}.dvi : Makefile ${GRAPHS} ${PROGRAMS} ${PICTURES} ${FIGURES} ${SOURCES} ${DATA} \ 100 glossary.tex style/style.tex ${Macros}/common.tex ${Macros}/ indexstyle local.bib ../../bibliography/pl.bib | ${Build}114 glossary.tex style/style.tex ${Macros}/common.tex ${Macros}/lstlang.sty ${Macros}/indexstyle local.bib ../../bibliography/pl.bib | ${Build} 101 115 # Must have *.aux file containing citations for bibtex 102 116 if [ ! -r ${basename $@}.aux ] ; then ${LaTeX} ${basename $@}.tex ; fi … … 112 126 ## Define the default recipes. 113 127 114 ${Build} :128 ${Build} : 115 129 mkdir -p ${Build} 116 130 -
doc/theses/colby_parsons_MMAth/benchmarks/actors/cfa/balance.cfa
rfa5e1aa5 rb7b3e41 31 31 32 32 d_actor ** actor_arr; 33 Allocation receive( d_actor & this, start_msg & msg ) with( this ) {33 allocation receive( d_actor & this, start_msg & msg ) with( this ) { 34 34 for ( i; Set ) { 35 *actor_arr[i + gstart] <<shared_msg;35 *actor_arr[i + gstart] | shared_msg; 36 36 } 37 37 return Nodelete; 38 38 } 39 39 40 Allocation receive( d_actor & this, d_msg & msg ) with( this ) {40 allocation receive( d_actor & this, d_msg & msg ) with( this ) { 41 41 if ( recs == rounds ) return Delete; 42 42 if ( recs % Batch == 0 ) { 43 43 for ( i; Batch ) { 44 *actor_arr[gstart + sends % Set] <<shared_msg;44 *actor_arr[gstart + sends % Set] | shared_msg; 45 45 sends += 1; 46 46 } … … 50 50 } 51 51 52 Allocation receive( filler & this, d_msg & msg ) { return Delete; }52 allocation receive( filler & this, d_msg & msg ) { return Delete; } 53 53 54 54 int main( int argc, char * argv[] ) { … … 163 163 #ifndef MULTI 164 164 for ( i; qpw ) 165 *actors[i * ActorsPerQueue] <<start_send;165 *actors[i * ActorsPerQueue] | start_send; 166 166 #else 167 167 for ( i; qpw * ActorProcs ) { 168 *actors[i * ActorsPerQueue] <<start_send;168 *actors[i * ActorsPerQueue] | start_send; 169 169 } 170 170 #endif 171 171 172 172 for ( i; FillActors ) 173 *filler_actors[i] <<shared_msg;173 *filler_actors[i] | shared_msg; 174 174 175 175 stop_actor_system(); -
doc/theses/colby_parsons_MMAth/benchmarks/actors/cfa/dynamic.cfa
rfa5e1aa5 rb7b3e41 24 24 25 25 uint64_t start_time; 26 Allocation receive( derived_actor & receiver, derived_msg & msg ) {26 allocation receive( derived_actor & receiver, derived_msg & msg ) { 27 27 if ( msg.cnt >= Times ) { 28 28 printf("%.2f\n", ((double)(bench_time() - start_time)) / ((double)Times) ); // ns … … 33 33 derived_actor * d_actor = malloc(); 34 34 (*d_actor){}; 35 *d_actor <<*d_msg;35 *d_actor | *d_msg; 36 36 return Delete; 37 37 } … … 62 62 derived_actor * d_actor = malloc(); 63 63 (*d_actor){}; 64 *d_actor <<*d_msg;64 *d_actor | *d_msg; 65 65 66 66 -
doc/theses/colby_parsons_MMAth/benchmarks/actors/cfa/executor.cfa
rfa5e1aa5 rb7b3e41 25 25 struct d_msg { inline message; } shared_msg; 26 26 27 Allocation receive( d_actor & this, d_msg & msg ) with( this ) {27 allocation receive( d_actor & this, d_msg & msg ) with( this ) { 28 28 if ( recs == rounds ) return Finished; 29 29 if ( recs % Batch == 0 ) { 30 30 for ( i; Batch ) { 31 gstart[sends % Set] <<shared_msg;31 gstart[sends % Set] | shared_msg; 32 32 sends += 1; 33 33 } … … 94 94 95 95 for ( i; Actors ) { 96 actors[i] <<shared_msg;96 actors[i] | shared_msg; 97 97 } // for 98 98 -
doc/theses/colby_parsons_MMAth/benchmarks/actors/cfa/matrix.cfa
rfa5e1aa5 rb7b3e41 24 24 } 25 25 26 Allocation receive( derived_actor & receiver, derived_msg & msg ) {26 allocation receive( derived_actor & receiver, derived_msg & msg ) { 27 27 for ( unsigned int i = 0; i < yc; i += 1 ) { // multiply X_row by Y_col and sum products 28 28 msg.Z[i] = 0; … … 103 103 104 104 for ( unsigned int r = 0; r < xr; r += 1 ) { 105 actors[r] <<messages[r];105 actors[r] | messages[r]; 106 106 } // for 107 107 -
doc/theses/colby_parsons_MMAth/benchmarks/actors/cfa/repeat.cfa
rfa5e1aa5 rb7b3e41 46 46 47 47 Client * cl; 48 Allocation receive( Server & this, IntMsg & msg ) { msg.val = 7; *cl <<msg; return Nodelete; }49 Allocation receive( Server & this, CharMsg & msg ) { msg.val = 'x'; *cl <<msg; return Nodelete; }50 Allocation receive( Server & this, StateMsg & msg ) { return Finished; }48 allocation receive( Server & this, IntMsg & msg ) { msg.val = 7; *cl | msg; return Nodelete; } 49 allocation receive( Server & this, CharMsg & msg ) { msg.val = 'x'; *cl | msg; return Nodelete; } 50 allocation receive( Server & this, StateMsg & msg ) { return Finished; } 51 51 52 52 void terminateServers( Client & this ) with(this) { 53 53 for ( i; Messages ) { 54 servers[i] <<stateMsg;54 servers[i] | stateMsg; 55 55 } // for 56 56 } 57 57 58 Allocation reset( Client & this ) with(this) {58 allocation reset( Client & this ) with(this) { 59 59 times += 1; 60 60 if ( times == Times ) { terminateServers( this ); return Finished; } 61 61 results = 0; 62 this <<stateMsg;62 this | stateMsg; 63 63 return Nodelete; 64 64 } 65 65 66 Allocation process( Client & this ) with(this) {66 allocation process( Client & this ) with(this) { 67 67 this.results++; 68 68 if ( results == 2 * Messages ) { return reset( this ); } … … 70 70 } 71 71 72 Allocation receive( Client & this, IntMsg & msg ) { return process( this ); }73 Allocation receive( Client & this, CharMsg & msg ) { return process( this ); }74 Allocation receive( Client & this, StateMsg & msg ) with(this) {72 allocation receive( Client & this, IntMsg & msg ) { return process( this ); } 73 allocation receive( Client & this, CharMsg & msg ) { return process( this ); } 74 allocation receive( Client & this, StateMsg & msg ) with(this) { 75 75 for ( i; Messages ) { 76 servers[i] <<intmsg[i];77 servers[i] <<charmsg[i];76 servers[i] | intmsg[i]; 77 servers[i] | charmsg[i]; 78 78 } 79 79 return Nodelete; … … 124 124 Client client; 125 125 cl = &client; 126 client <<stateMsg;126 client | stateMsg; 127 127 128 128 stop_actor_system(); -
doc/theses/colby_parsons_MMAth/benchmarks/actors/cfa/static.cfa
rfa5e1aa5 rb7b3e41 23 23 24 24 uint64_t start_time; 25 Allocation receive( derived_actor & receiver, derived_msg & msg ) {25 allocation receive( derived_actor & receiver, derived_msg & msg ) { 26 26 if ( msg.cnt >= Times ) { 27 27 printf("%.2f\n", ((double)(bench_time() - start_time)) / ((double)Times) ); // ns … … 29 29 } 30 30 msg.cnt++; 31 receiver <<msg;31 receiver | msg; 32 32 return Nodelete; 33 33 } … … 58 58 derived_actor actor; 59 59 60 actor <<msg;60 actor | msg; 61 61 62 62 stop_actor_system(); -
doc/theses/colby_parsons_MMAth/benchmarks/actors/plotData.py
rfa5e1aa5 rb7b3e41 166 166 for idx, arr in enumerate(data): 167 167 plt.errorbar( procs, arr, [bars[idx][0], bars[idx][1]], capsize=2, marker=next(marker) ) 168 marker = itertools.cycle(('o', 's', 'D', 'x', 'p', '^', 'h', '*', 'v' )) 168 169 if currBench == Bench.Executor or currBench == Bench.Matrix or currBench == Bench.Balance_One or currBench == Bench.Repeat: 169 170 plt.yscale("log") -
doc/theses/colby_parsons_MMAth/benchmarks/channels/plotData.py
rfa5e1aa5 rb7b3e41 130 130 for idx, arr in enumerate(data): 131 131 plt.errorbar( procs, arr, [bars[idx][0], bars[idx][1]], capsize=2, marker=next(marker) ) 132 132 marker = itertools.cycle(('o', 's', 'D', 'x', 'p', '^', 'h', '*', 'v' )) 133 133 plt.yscale("log") 134 134 # plt.ylim(1, None) -
doc/theses/colby_parsons_MMAth/benchmarks/mutex_stmt/plotData.py
rfa5e1aa5 rb7b3e41 103 103 for idx, arr in enumerate(data): 104 104 plt.errorbar( procs, arr, [bars[idx][0], bars[idx][1]], capsize=2, marker=next(marker) ) 105 marker = itertools.cycle(('o', 's', 'D', 'x', 'p', '^', 'h', '*', 'v' )) 105 106 plt.yscale("log") 106 107 plt.xticks(procs) -
doc/theses/colby_parsons_MMAth/code/basic_actor_example.cfa
rfa5e1aa5 rb7b3e41 19 19 } 20 20 21 Allocation receive( derived_actor & receiver, derived_msg & msg ) {21 allocation receive( derived_actor & receiver, derived_msg & msg ) { 22 22 printf("The message contained the string: %s\n", msg.word); 23 23 return Finished; // Return allocation status of Finished now that the actor is done work -
doc/theses/colby_parsons_MMAth/diagrams/gulp.tikz
rfa5e1aa5 rb7b3e41 87 87 88 88 % Text Node 89 \draw ( 23,6) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Worker}};89 \draw (15,6) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Executor Thread}}; 90 90 % Text Node 91 \draw (85, 18) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Empty local queue}};91 \draw (85,20) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Empty local queue}}; 92 92 % Text Node 93 93 \draw (8,197) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Sharded message queues}}; … … 101 101 \draw (70,71) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Gulps queue 0}}; 102 102 % Text Node 103 \draw (3 12,6) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Worker}};103 \draw (303,6) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Executor Thread}}; 104 104 % Text Node 105 \draw (374, 18) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Local queue}};105 \draw (374,21) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Local queue}}; 106 106 % Text Node 107 107 \draw (297,198) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Sharded message queues}}; -
doc/theses/colby_parsons_MMAth/diagrams/inverted_actor.tikz
rfa5e1aa5 rb7b3e41 275 275 276 276 % Text Node 277 \draw (2 45,-2) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Worker Threads}};277 \draw (258,-2) node [anchor=north west][inner sep=0.75pt] [align=left] {{\small Executor}}; 278 278 % Text Node 279 \draw (155,-2) node [anchor=north west][inner sep=0.75pt] [align=left] {{\ footnotesizeActors}};279 \draw (155,-2) node [anchor=north west][inner sep=0.75pt] [align=left] {{\small Actors}}; 280 280 % Text Node 281 \draw (21,73) node [anchor=north west][inner sep=0.75pt] [align=left] {{\ footnotesize Message}\\{\footnotesizeQueues}};281 \draw (21,73) node [anchor=north west][inner sep=0.75pt] [align=left] {{\small Message}\\{\small Queues}}; 282 282 283 283 -
doc/theses/colby_parsons_MMAth/diagrams/standard_actor.tikz
rfa5e1aa5 rb7b3e41 182 182 183 183 % Text Node 184 \draw (1 86,6) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesize Worker Threads}};184 \draw (197,6) node [anchor=north west][inner sep=0.75pt] [align=left] {{\small Executor}}; 185 185 % Text Node 186 \draw (91,9) node [anchor=north west][inner sep=0.75pt] [align=left] {{\ footnotesizeActors}};186 \draw (91,9) node [anchor=north west][inner sep=0.75pt] [align=left] {{\small Actors}}; 187 187 % Text Node 188 \draw ( 81,207) node [anchor=north west][inner sep=0.75pt] [align=left] {{\footnotesizeMailboxes}};188 \draw (78,207) node [anchor=north west][inner sep=0.75pt] [align=left] {{\small Mailboxes}}; 189 189 190 190 -
doc/theses/colby_parsons_MMAth/glossary.tex
rfa5e1aa5 rb7b3e41 37 37 \newabbreviation{toctou}{TOCTOU}{\Newterm{time-of-check to time-of-use}} 38 38 39 \newglossaryentry{actor} 40 { 39 \newglossaryentry{actor}{ 41 40 name=actor, 42 41 description={A basic unit of an actor system that can store local state and send messages to other actors.} 43 42 } 44 43 45 \newglossaryentry{impl_concurrency} 46 { 44 \newglossaryentry{gulp}{ 45 name={gulp}, 46 first={\Newterm{gulp}}, 47 description={Move the contents of message queue to a local queue of the executor thread using a single atomic instruction.} 48 } 49 50 \newglossaryentry{impl_concurrency}{ 47 51 name=implicit concurrency, 52 first={\Newterm{implicit concurrency}}, 48 53 description={A class of concurrency features that abstract away explicit thread synchronization and mutual exclusion.} 49 54 } 50 55 51 \newglossaryentry{actor_model} 52 { 56 \newglossaryentry{actor_model}{ 53 57 name=actor model, 58 first={\Newterm{actor model}}, 54 59 description={A concurrent computation model, where tasks are broken into units of work that are distributed to actors in the form of messages.} 55 60 } 56 61 57 \newglossaryentry{actor_system} 58 { 62 \newglossaryentry{actor_system}{ 59 63 name=actor system, 64 first={\Newterm{actor system}}, 60 65 description={An implementation of the actor model.} 61 66 } 62 67 63 \newglossaryentry{synch_multiplex} 64 { 68 \newglossaryentry{synch_multiplex}{ 65 69 name=synchronous multiplexing, 70 first={\Newterm{synchronous multiplexing}}, 66 71 description={synchronization on some subset of a set of resources.} 67 72 } -
doc/theses/colby_parsons_MMAth/local.bib
rfa5e1aa5 rb7b3e41 100 100 } 101 101 102 @misc{go:sched, 103 author = "The Go Programming Language", 104 title = "src/runtime/proc.go", 105 howpublished = {\href{https://go.dev/src/runtime/proc.go}}, 106 note = "[Online; accessed 23-May-2023]" 107 } 108 102 109 @misc{go:selectref, 103 110 author = "The Go Programming Language Specification", … … 144 151 @misc{linux:select, 145 152 author = "Linux man pages", 146 title = "select(2) —Linux manual page",153 title = "select(2) - Linux manual page", 147 154 howpublished = {\href{https://man7.org/linux/man-pages/man2/select.2.html}}, 148 155 note = "[Online; accessed 23-May-2023]" … … 151 158 @misc{linux:poll, 152 159 author = "Linux man pages", 153 title = "poll(2) —Linux manual page",160 title = "poll(2) - Linux manual page", 154 161 howpublished = {\href{https://man7.org/linux/man-pages/man2/poll.2.html}}, 155 162 note = "[Online; accessed 23-May-2023]" … … 158 165 @misc{linux:epoll, 159 166 author = "Linux man pages", 160 title = "epoll(7) —Linux manual page",167 title = "epoll(7) - Linux manual page", 161 168 howpublished = {\href{https://man7.org/linux/man-pages/man7/epoll.7.html}}, 162 169 note = "[Online; accessed 23-May-2023]" -
doc/theses/colby_parsons_MMAth/style/style.tex
rfa5e1aa5 rb7b3e41 2 2 \CFAStyle % CFA code-style 3 3 \lstset{language=CFA} % default language 4 \setlength{\gcolumnposn}{3in} 4 5 5 6 \newcommand{\newtermFont}{\emph} 6 7 \newcommand{\Newterm}[1]{\newtermFont{#1}} 8 %\renewcommand{\newterm}[1]{\newtermFont{#1}} 7 9 8 10 \newcommand{\code}[1]{\lstinline[language=CFA]{#1}} -
doc/theses/colby_parsons_MMAth/text/CFA_intro.tex
rfa5e1aa5 rb7b3e41 179 179 \end{cfa} 180 180 181 \subsection{Inheritance} 181 \subsection{Inheritance}\label{s:Inheritance} 182 182 Inheritance in \CFA is taken from Plan-9 C's nominal inheritance. 183 183 In \CFA, @struct@s can @inline@ another struct type to gain its fields and masquerade as that type. -
doc/theses/colby_parsons_MMAth/text/actors.tex
rfa5e1aa5 rb7b3e41 6 6 7 7 % C_TODO: add citations throughout chapter 8 Actors are a concurrent feature that abstracts threading away from a user, and instead provides \gls{actor}s and messages as building blocks for concurrency. 9 Actors are another message passing concurrency feature, similar to channels, but with more abstraction. 10 Actors 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. 11 The 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. 8 Actors are an indirect concurrent feature that abstracts threading away from a programmer, and instead provides \gls{actor}s and messages as building blocks for concurrency, where message passing means there is no shared data to protect, making actors amenable in a distributed environment. 9 Actors are another message passing concurrency feature, similar to channels but with more abstraction, and are in the realm of \gls{impl_concurrency}, where programmers write concurrent code without dealing with explicit thread creation or interaction. 10 The 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. 12 11 Before 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 12 14 \section{The Actor Model} 15 The 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}. 16 Actors execute asynchronously upon receiving a message and can modify their own state, make decisions, spawn more actors, and send messages to other actors. 17 The actor model is an implicit model of concurrency. 18 As such, one strength of the actor model is that it abstracts away many considerations that are needed in other paradigms of concurrent computation. 19 Mutual 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} 22 An implementation of the actor model with a community of actors is called an actor system. 23 Actor systems largely follow the actor model, but differ in some ways. 24 While 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. 25 Another way an actor system varies from the model is that actors are often allowed to access non-local state. 26 When this occurs it can complicate the implementation as this will break any mutual exclusion guarantees given by accessing only local state. 13 \section{Actor Model} 14 The actor model is a concurrent paradigm where computation is broken into units of work called actors, and the data for computation is distributed to actors in the form of messages~\cite{Hewitt73}. 15 An actor is composed of a \Newterm{mailbox} (message queue) and a set of \Newterm{behaviours} that receive from the mailbox to perform work. 16 Actors execute asynchronously upon receiving a message and can modify their own state, make decisions, spawn more actors, and send messages to other actors. 17 Because the actor model is implicit concurrency, its strength is that it abstracts away many details and concerns needed in other concurrent paradigms. 18 For example, mutual exclusion and locking are rarely relevant concepts in an actor model, as actors typically only operate on local state. 19 20 An actor does not have a thread. 21 An actor is executed by an underlying \Newterm{executor} (kernel thread-pool) that fairly invokes each actor, where an actor invocation processes one or more messages from its mailbox. 22 The default number of executor threads is often proportional to the number of computer cores to achieve good performance. 23 An executor is often tunable with respect to the number of kernel threads and its scheduling algorithm, which optimize for specific actor applications and workloads \see{end of Section~\ref{s:CFAActor}}. 24 25 \subsection{Classic Actor System} 26 An implementation of the actor model with a community of actors is called an actor system. 27 Actor systems largely follow the actor model, but can differ in some ways. 28 While the semantics of message \emph{send} is asynchronous, the implementation may be synchronous or a combination. 29 The default semantics for message \emph{receive} is FIFO, so an actor receives messages from its mailbox in temporal (arrival) order; 30 however, messages sent among actors arrive in any order. 31 Some actor systems provide priority-based mailboxes and/or priority-based message-selection within a mailbox, where custom message dispatchers search among or within a mailbox(es) with a predicate for specific kinds of actors and/or messages. 32 Some actor systems provide a shared mailbox where multiple actors receive from a common mailbox~\cite{Akka}, which is contrary to the no-sharing design of the basic actor-model (and requires additional locking). 33 For non-FIFO service, some notion of fairness (eventual progress) must exist, otherwise messages have a high latency or starve, \ie never received. 34 Finally, some actor systems provide multiple typed-mailboxes, which then lose the actor-\lstinline{become} mechanism (see Section~\ref{s:SafetyProductivity}). 35 %While 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. 36 Another way an actor system varies from the model is allowing access to shared global-state. 37 When this occurs, it complicates the implementation as this breaks any implicit mutual-exclusion guarantees when only accessing local-state. 27 38 28 39 \begin{figure} 29 40 \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}}} 41 \subfloat[Actor-centric system]{\label{f:standard_actor}\input{diagrams/standard_actor.tikz}} & 42 \subfloat[Message-centric system]{\label{f:inverted_actor}\raisebox{.1\height}{\input{diagrams/inverted_actor.tikz}}} 32 43 \end{tabular} 33 44 \caption{Classic and inverted actor implementation approaches with sharded queues.} 34 45 \end{figure} 35 46 36 \section{\CFA Actors} 37 Actor systems \cite{} have often been implemented as an actor-centric system. 38 As such they are constructed as a set of actors that are scheduled and run on some underlying threads. 39 Each actor has their own queue for receiving messages, sometimes called a mailbox. 40 When 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. 41 This approach can be implemented with a global queue of actors, but is often implemented as each worker thread owning a queue of actors. 42 This is known as sharding the actor queue, which is done to decrease contention across worker threads. 43 A diagram of an actor-centric system with a sharded actor queue is shown in Figure \ref{f:standard_actor}. 47 \subsection{\CFA Actor System} 48 Figure~\ref{f:standard_actor} shows an actor system designed as \Newterm{actor-centric}, where a set of actors are scheduled and run on underlying executor threads~\cite{CAF,Akka,ProtoActor}. 49 The simplest design has a single global queue of actors accessed by the executor threads, but this approach results in high contention as both ends of the queue by the executor threads. 50 The more common design is to \Newterm{shard} the single queue among the executor threads, where actors are permanently assigned or can float among the queues. 51 Sharding significantly decreases contention among executor threads adding and removing actors to/from a queue. 52 Finally, each actor has a receive queue of messages (mailbox), which is a single consumer, multi-producer queue, \ie only the actor removes from the mailbox but multiple actors can attach messages. 53 When an actor receives a message in its mailbox, the actor is marked ready and scheduled by a thread to run the actor's current work unit on the message(s). 44 54 45 55 % cite parallel theatre and our paper 46 The actor system in \CFA is instead message-centric, an uses what is called an inverted actor system \cite{}. 47 In this inverted actor system instead of each worker thread owning a queue of actors, they each own a queue of messages. 48 This 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. 49 Since multiple actors belong to each message queue, messages to each actor are interleaved in the queue. 50 In this scheme work is consumed from their queue and executed by underlying threads. 51 In 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. 52 A diagram of an inverted actor scheme with a sharded message queue is shown in Figure \ref{f:inverted_actor}. 53 The arrows from the message queues to the actors in the diagram indicate interleaved messages addressed to each actor. 54 55 The actor system in \CFA builds on top of the architecture laid out in High-Performance Extended Actors \cite{} and adds the following contributions: 56 56 Figure \ref{f:inverted_actor} shows an actor system designed as \Newterm{message-centric}, where a set of messages are scheduled and run on underlying executor threads~\cite{uC++,Nigro21}. 57 Again, the simplest design has a single global queue of messages accessed by the executor threads, but this approach has the same contention problem by the executor threads. 58 Therefore, the messages (mailboxes) are sharded and executor threads schedule each message, which points to its corresponding actor. 59 Here, an actor's messages are permanently assigned to one queue to ensure FIFO receiving and/or reduce searching for specific actor/messages. 60 Since multiple actors belong to each message queue, actor messages are interleaved on a queue. 61 This design is \Newterm{inverted} because actors belong to a message queue, whereas in the classic approach a message queue belongs to each actor. 62 % In this inverted actor system instead of each executor threads owning a queue of actors, they each own a queue of messages. 63 % In this scheme work is consumed from their queue and executed by underlying threads. 64 The inverted model can be taken a step further by sharding the message queues for each executor threads, so each executor thread owns a set of queues and cycles through them. 65 Again, this extra level of sharding is to reduce queue contention. 66 % The arrows from the message queues to the actors in the diagram indicate interleaved messages addressed to each actor. 67 68 The actor system in \CFA uses a message-centric design, adopts several features from my prior actor work in \uC~\cite{}, and adds the following contributions related to \CFA: 57 69 \begin{enumerate}[topsep=5pt,itemsep=3pt,parsep=0pt] 58 70 \item 59 Provide s insight into the impact of envelope allocation in actor systems.60 In 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.61 This 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.62 This dynamic allocation occurs once per message sent. 63 This is a large source of contention on the memory allocator since all these allocations occur concurrently. 64 A novel data structure is used to consolidate allocations to improve performance by minimizing contention on the allocator.65 66 \item 67 I ntroduces work stealing in the inverted actor system.68 Work stealing in actor-centric systems tends to involve stealing one or more actors. 69 In the inverted system the notion of stealing queues is introduced. 70 The 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 73 Introduces 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 76 I mproves 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 79 Provide sa suite of safety and productivity features including static-typing, detection of erroneous message sends, statistics tracking, and more.71 Provide insight into the impact of envelope allocation in actor systems. 72 In all actor systems, dynamic allocation is needed to ensure the lifetime of a unit of work persists from its creation until the unit of work is executed. 73 This allocation is often called an \Newterm{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. 74 This dynamic allocation occurs once per message sent. 75 Unfortunately, the high rate of message sends in an actor system results in significant contention on the memory allocator. 76 A novel data structure is introduced to consolidate allocations to improve performance by minimizing allocator contention. 77 78 \item 79 Improve performance of the inverted actor system using multiple approaches to minimize contention on queues, such as queue gulping and avoiding atomic operations. 80 81 \item 82 Introduce work stealing in the inverted actor system. 83 Work stealing in an actor-centric system involves stealing one or more actors among executor threads. 84 In the inverted system, the notion of stealing message queues is introduced. 85 The queue stealing is implemented such that the act of stealing work does not contend with non-stealing executor threads running actors. 86 87 \item 88 Introduce and evaluate a timestamp-based work-stealing heuristic with the goal of maintaining non-workstealing performance in work-saturated workloads and improving performance on unbalanced workloads. 89 90 \item 91 Provide a suite of safety and productivity features including static-typing, detection of erroneous message sends, statistics tracking, and more. 80 92 \end{enumerate} 81 93 82 \section{\CFA Actor Syntax} 83 \CFA is not an object oriented language and it does not have run-time type information (RTTI). 84 As such all message sends and receives between actors occur using exact type matching. 85 To use actors in \CFA you must \code{\#include <actors.hfa>}. 86 To create an actor type one must define a struct which inherits from the base \code{actor} struct via the \code{inline} keyword. 87 This is the Plan-9 C-style nominal inheritance discussed in Section \ref{s:poly}. 88 Similarly to create a message type a user must define a struct which \code{inline}'s the base \code{message} struct. 89 90 \begin{cfa} 91 struct derived_actor { 92 inline actor; // Plan-9 C inheritance 93 }; 94 void ?{}( derived_actor & this ) { // Default ctor 95 ((actor &)this){}; // Call to actor ctor 96 } 97 98 struct derived_msg { 99 inline message; // Plan-9 C nominal inheritance 100 char word[12]; 101 }; 102 void ?{}( derived_msg & this, char * new_word ) { // Overloaded ctor 103 ((message &) this){ Nodelete }; // Passing allocation to ctor 104 strcpy(this.word, new_word); 105 } 106 107 Allocation 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 112 int 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; 94 \section{\CFA Actor}\label{s:CFAActor} 95 \CFA is not an object oriented language and it does not have \gls{rtti}. 96 As such, all message sends and receives among actors can only occur using static type-matching, as in Typed-Akka~\cite{AkkaTyped}. 97 Figure~\ref{f:BehaviourStyles} contrasts dynamic and static type-matching. 98 Figure~\ref{l:dynamic_style} shows the dynamic style with a heterogeneous message receive and an indirect dynamic type-discrimination for message processing. 99 Figure~\ref{l:static_style} shows the static style with a homogeneous message receive and a direct static type-discrimination for message processing. 100 The static-typing style is safer because of the static check and faster because there is no dynamic type-discrimination. 101 The dynamic-typing style is more flexible because multiple kinds of messages can be handled in a behaviour condensing the processing code. 102 103 \begin{figure} 104 \centering 105 106 \begin{lrbox}{\myboxA} 107 \begin{cfa}[morekeywords=case] 108 allocation receive( message & msg ) { 109 case( @msg_type1@, msg ) { // discriminate type 110 ... msg_d-> ...; // msg_type1 msg_d 111 } else case( @msg_type2@, msg ) { 112 ... msg_d-> ...; // msg_type2 msg_d 113 ... 119 114 } 120 115 \end{cfa} 121 122 The above code is a simple actor program in \CFA. 123 There is one derived actor type and one derived message type. 124 A single message containing a string is sent from the program main to an actor. 125 Key things to highlight include the \code{receive} signature, and calls to \code{start_actor_system}, and \code{stop_actor_system}. 126 To define a behaviour for some derived actor and derived message type, one must declare a routine with the signature: 116 \end{lrbox} 117 118 \begin{lrbox}{\myboxB} 127 119 \begin{cfa} 128 Allocation receive( derived_actor & receiver, derived_msg & msg ) 120 allocation receive( @msg_type1@ & msg ) { 121 ... msg ...; 122 } 123 allocation receive( @msg_type2@ & msg ) { 124 ... msg ...; 125 } 126 ... 129 127 \end{cfa} 130 Where \code{derived_actor} and \code{derived_msg} can be any derived actor and derived message types respectively. 131 The return value of \code{receive} must be a value from the \code{Allocation} enum: 128 \end{lrbox} 129 \subfloat[dynamic typing]{\label{l:dynamic_style}\usebox\myboxA} 130 \hspace*{10pt} 131 \vrule 132 \hspace*{10pt} 133 \subfloat[static typing]{\label{l:static_style}\usebox\myboxB} 134 \caption{Behaviour Styles} 135 \label{f:BehaviourStyles} 136 \end{figure} 137 138 \begin{figure} 139 \centering 140 132 141 \begin{cfa} 133 enum Allocation { Nodelete, Delete, Destroy, Finished }; 142 // actor 143 struct my_actor { 144 @inline actor;@ $\C[3.25in]{// Plan-9 C inheritance}$ 145 }; 146 // messages 147 struct str_msg { 148 char str[12]; 149 @inline message;@ $\C{// Plan-9 C inheritance}$ 150 }; 151 void ?{}( str_msg & this, char * str ) { strcpy( this.str, str ); } $\C{// constructor}$ 152 struct int_msg { 153 int i; 154 @inline message;@ $\C{// Plan-9 C inheritance}$ 155 }; 156 // behaviours 157 allocation receive( my_actor &, @str_msg & msg@ ) with(msg) { 158 sout | "string message \"" | str | "\""; 159 return Nodelete; $\C{// actor not finished}$ 160 } 161 allocation receive( my_actor &, @int_msg & msg@ ) with(msg) { 162 sout | "integer message" | i; 163 return Nodelete; $\C{// actor not finished}$ 164 } 165 int main() { 166 str_msg str_msg{ "Hello World" }; $\C{// constructor call}$ 167 int_msg int_msg{ 42 }; $\C{// constructor call}$ 168 start_actor_system(); $\C{// sets up executor}$ 169 my_actor actor; $\C{// default constructor call}$ 170 @actor | str_msg | int_msg;@ $\C{// cascade sends}$ 171 @actor | int_msg;@ $\C{// send}$ 172 @actor | finished_msg;@ $\C{// send => terminate actor (deallocation deferred)}$ 173 stop_actor_system(); $\C{// waits until actors finish}\CRT$ 174 } // deallocate int_msg, str_msg, actor 134 175 \end{cfa} 135 The \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. 136 In 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. 137 For messages, they either default to \code{Nodelete}, or they can be passed an \code{Allocation} via the \code{message} constructor. 138 Message state can be updated via a call to: 176 \caption{\CFA Actor Syntax} 177 \label{f:CFAActor} 178 \end{figure} 179 180 Figure~\ref{f:CFAActor} shows a complete \CFA actor example starting with the actor type @my_actor@ created by defining a @struct@ that inherits from the base @actor@ @struct@ via the @inline@ keyword. 181 This inheritance style is the Plan-9 C-style inheritance discussed in Section~\ref{s:Inheritance}. 182 Similarly, the message types @str_msg@ and @int_msg@ are created by defining a @struct@ that inherits from the base @message@ @struct@ via the @inline@ keyword. 183 Only @str_msg@ needs a constructor to copy the C string; 184 @int_msg@ is initialized using its \CFA auto-generated constructors. 185 There are two matching @receive@ (behaviour) routines that process the corresponding typed messages. 186 Both @receive@ routines use a @with@ clause so message fields are not qualified and return @Nodelete@ indicating the actor is not finished. 187 Also, all messages are marked with @Nodelete@ as their default allocation state. 188 The program main begins by creating two messages on the stack. 189 Then the executor system is started by calling @start_actor_system@. 190 Now an actor is created on the stack and four messages are sent it using operator @?|?@. 191 The last message is the builtin @finish_msg@, which returns @Finished@ to an executor thread, causing it to removes the actor from the actor system \see{Section~\ref{s:ActorBehaviours}}. 192 The call to @stop_actor_system@ blocks the program main until all actors are finished and removed from the actor system. 193 The program main ends by deleting the actor and two messages from the stack. 194 The output for the program is: 139 195 \begin{cfa} 140 void set_allocation( message & this, Allocation state ) 196 string message "Hello World" 197 integer message 42 198 integer message 42 141 199 \end{cfa} 142 200 143 The following describes the use of each of the \code{Allocation} values: 144 145 \begin{description} 146 \item[\LstBasicStyle{\textbf{Nodelete}}] 147 tells the executor that no action is to be taken with regard to a message or actor with this status. 148 This indicates that the actor will receive future behaviours, and that a message may be reused. 149 150 \item[\LstBasicStyle{\textbf{Delete}}] 151 tells the executor to call the appropriate destructor and then deallocate the respective actor or message. 152 This status is typically used with dynamically allocated actors and messages. 153 154 \item[\LstBasicStyle{\textbf{Destroy}}] 155 tells the executor to call the object's destructor. 156 The executor will not deallocate the respective actor or message. 157 This status is typically used with dynamically allocated actors and messages whose storage will be reused. 158 159 \item[\LstBasicStyle{\textbf{Finished}}] 160 tells the executor to mark the respective actor as being finished executing. 161 In this case the executor will not call any destructors or deallocate any objects. 162 This status is used when the actors are stack allocated or if the user wants to manage deallocation of actors themselves. 163 In 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. 164 As 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 167 For the actor system to gracefully terminate, all actors must have returned a status other than \code{Nodelete}. 168 Once an actor's allocation status has been set to something other than \code{Nodelete}, it is erroneous for the actor to receive a message. 169 Similarly messages cannot be safely reused after their related behaviour if their status is not \code{Nodelete}. 170 Note, 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 172 The calls to \code{start_actor_system}, and \code{stop_actor_system} mark the start and end of a \CFA actor system. 173 The 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. 179 It 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. 182 Executor configuration options include number of worker threads, number of queues, number of processors, and a few other toggles. 183 184 All 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 186 All message sends are done using the left shift operater, \ie <<, similar to the syntax of \CC's output. 187 The signature of the left shift operator is: 201 \subsection{Actor Behaviours}\label{s:ActorBehaviours} 202 In general, a behaviour for some derived actor and derived message type is defined with following signature: 188 203 \begin{cfa} 189 Allocation ?<<?( derived_actor & receiver, derived_msg & msg )204 allocation receive( my_actor & receiver, my_msg & msg ) 190 205 \end{cfa} 191 192 An astute eye will notice that this is the same signature as the \code{receive} routine which is no coincidence. 193 The \CFA compiler generates a \code{?<<?} routine definition and forward declaration for each \code{receive} routine that has the appropriate signature. 194 The 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. 195 As 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 206 where @my_actor@ and @my_msg@ inherit from types @actor@ and @message@, respectively. 207 The return value of @receive@ must be a value from enumerated type, @allocation@: 208 \begin{cfa} 209 enum allocation { Nodelete, Delete, Destroy, Finished }; 210 \end{cfa} 211 The values represent a set of actions that dictate what the executor does with an actor or message after a given behaviour returns. 212 For actors, the @receive@ routine returns the @allocation@ status to the executor, which takes the appropriate action. 213 For messages, either the default allocation, @Nodelete@, or any changed value in the message is examined by the executor, which takes the appropriate action. 214 Message state is updated via a call to: 215 \begin{cfa} 216 void set_allocation( message & this, allocation state ) 217 \end{cfa} 218 219 In detail, the actions taken by an executor for each of the @allocation@ values are: 220 221 \noindent@Nodelete@ 222 tells the executor that no action is to be taken with regard to an actor or message. 223 This status is used when an actor continues receiving messages or a message may be reused. 224 225 \noindent@Delete@ 226 tells the executor to call the object's destructor and deallocate (delete) the object. 227 This status is used with dynamically allocated actors and messages when they are not reused. 228 229 \noindent@Destroy@ 230 tells the executor to call the object's destructor, but not deallocate the object. 231 This status is used with dynamically allocated actors and messages whose storage is reused. 232 233 \noindent@Finished@ 234 tells the executor to mark the respective actor as finished executing, but not call the object's destructor nor deallocate the object. 235 This status is used when actors or messages are global or stack allocated, or a programmer wants to manage deallocation themselves. 236 237 For the actor system to terminate, all actors must have returned a status other than @Nodelete@. 238 After an actor is terminated, it is erroneous to send messages to it. 239 Similarly, after a message is terminated, it cannot be sent to an actor. 240 Note, it is safe to construct an actor or message with a status other than @Nodelete@, since the executor only examines the allocation action after a behaviour returns. 241 242 \subsection{Actor Envelopes}\label{s:envelope} 243 As stated, each message, regardless of where it is allocated, can be sent to an arbitrary number of actors, and hence, appear on an arbitrary number of message queues. 244 Because a C program manages message lifetime, messages cannot be copied for each send, otherwise who manages the copies. 245 Therefore, it up to the actor program to manage message life-time across receives. 246 However, for a message to appear on multiple message queues, it needs an arbitrary number of associated destination behaviours. 247 Hence, there is the concept of an envelop, which is dynamically allocated on each send, that wraps a message with any extra implementation fields needed to persist between send and receive. 248 Managing the envelop is straightforward because it is created at the send and deleted after the receive, \ie there is 1:1 relationship for an envelop and a many to one relationship for a message. 249 250 % In actor systems, messages are sent and received by actors. 251 % When a actor receives a message it executes its behaviour that is associated with that message type. 252 % However 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. 253 % Furthermore 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. 254 % All these requirements are fulfilled by a construct called an envelope. 255 % The envelope wraps up the unit of work and also stores any information needed by data structures such as link fields. 256 257 % One may ask, "Could the link fields and other information be stored in the message?". 258 % This is a good question to ask since messages also need to have a lifetime that persists beyond the work it delivers. 259 % However, if one were to use messages as envelopes then a message would not be able to be sent to multiple actors at a time. 260 % Therefore 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. 261 262 \subsection{Actor System}\label{s:ActorSystem} 263 The calls to @start_actor_system@, and @stop_actor_system@ mark the start and end of a \CFA actor system. 264 The call to @start_actor_system@ sets up an executor and executor threads for the actor system. 265 It is possible to have multiple start/stop scenarios in a program. 266 267 @start_actor_system@ has three overloaded signatures that vary the executor's configuration: 268 269 \noindent@void start_actor_system()@ 270 configures the executor to implicitly use all preallocated kernel-threads (processors), \ie the processors created by the program main prior to starting the actor system. 271 When the number of processors is greater than 1, each executor's message queue is sharded by a factor of 16 to reduce contention, \ie for 4 executor threads (processors), there is a total of 4 $\times$ 16 message queues evenly distributed across the executor threads. 272 273 \noindent@void start_actor_system( size_t num_thds )@ 274 configures the number of executor threads to @num_thds@, with the same message queue sharding. 275 276 \noindent@void start_actor_system( executor & this )@ 277 allows the programmer to explicitly create and configure an executor for use by the actor system. 278 Executor configuration options include are discussed in Section~\ref{s:executor}. 279 280 \noindent 281 All actors must be created \emph{after} calling @start_actor_system@ so the executor can keep track of the number of actors that have entered the system but not yet terminated. 282 283 \subsection{Actor Send}\label{s:ActorSend} 284 All message sends are done using the vertical-bar (bit-or) operator, @?|?@, similar to the syntax of the \CFA stream I/O. 285 Hence, programmers must write a matching @?|?@ routine for each @receive@ routine, which is awkward and generates a maintenance problem that must be solved. 286 \CFA's current best approach for creating a generic @?|?@ routine requires users to create routines for their actor and message types that access the base type. 287 Since these routines are not complex, they can be generated using macros that are used to annotate the user-defined actor and message types. 288 This approach is used in \CFA's intrusive list data structure. 289 This is not much better than asking users to write the @?|?@ routine themselves in terms of maintenance, since the user needs to remember the boilerplate macro annotation. 290 291 As stated, \CFA does not have named inheritance with RTTI. 292 \CFA does have a preliminary form of virtual routines, but it is not mature enough for use in this work. 293 Virtuals would provide a mechanism to write a single generic @?|?@ routine taking a base actor and message type, that would dynamically select the @receive@ routine from the actor argument. 294 Note, virtuals are not needed for the send; Plan-9 inheritance is sufficient because only the inherited fields are needed during the message send (only upcasting is needed). 295 296 Therefore, a template-like approach was chosen, where the compiler generates a matching @?|?@ routine for each @receive@ routine it finds with the correct actor/message type-signature. 297 This approach requires no annotation or additional code to be written by users, thus it resolves the maintenance problem. 298 (When the \CFA virtual routines mature, it should be possible to seamlessly transition to it from the template approach.) 299 300 Figure~\ref{f:send_gen} shows the generated send routine for the @int_msg@ receive in Figure~\ref{f:CFAActor}. 301 Operator @?|?@ has the same parameter signature as the corresponding @receive@ routine and returns an @actor@ so the operator can be cascaded. 302 The routine sets @rec_fn@ to the matching @receive@ routine using the left-hand type to perform the selection. 303 Then the routine packages the base and derived actor and message and actor, along with the receive routine into an \hyperref[s:envelope]{envelope}. 304 Finally, the envelop is added to the executor queue designated by the actor using the executor routine @send@. 305 306 \begin{figure} 307 \begin{cfa} 308 $\LstCommentStyle{// from Figure~\ref{f:CFAActor}}$ 309 struct my_actor { inline actor; }; $\C[3.75in]{// actor}$ 310 struct int_msg { inline message; int i; }; $\C{// message}$ 311 allocation receive( @my_actor &, int_msg & msg@ ) {...} $\C{// receiver}$ 312 313 // compiler generated send operator 314 typedef allocation (*receive_t)( actor &, message & ); 315 actor & ?|?( @my_actor & receiver, int_msg & msg@ ) { 316 allocation (*rec_fn)( my_actor &, int_msg & ) = @receive@; // deduce receive routine 317 request req{ &receiver, (actor *)&receiver, &msg, (message *)&msg, (receive_t)rec_fn }; 318 send( receiver, req ); $\C{// queue message for execution}\CRT$ 319 return receiver; 320 } 321 \end{cfa} 322 \caption{Generated Send Operator} 323 \label{f:send_gen} 324 \end{figure} 325 326 \subsection{Actor Termination}\label{s:ActorTerm} 327 During a message send, the receiving actor and message being sent are stored via pointers in the envelope. 328 These pointers have the base actor and message types, so type information of the actor and message is lost and then recovered later when the typed receive routine is called. 329 After the receive routine is done, the executor must clean up the actor and message according to their allocation status. 330 If the allocation status is @Delete@ or @Destroy@, the appropriate destructor must be called by the executor. 331 This poses a problem; the correct type of the actor or message is not available to the executor, but it needs to call the right destructor! 332 This requires downcasting from the base type to derived type, which requires a virtual system. 333 Thus, a rudimentary destructor-only virtual system was added to \CFA as part of this work. 334 This virtual system is used via Plan-9 inheritance of the @virtual_dtor@ type, shown in Figure~\ref{f:VirtDtor}. 335 The @virtual_dtor@ type maintains a pointer to the start of the object, and a pointer to the correct destructor. 336 When a type inherits the @virtual_dtor@ type, the compiler adds code to its destructor to make sure that any destructor calls along this segment of the inheritance tree is called are intercepted, and restart at the appropriate destructor for that object. 337 338 \begin{figure} 339 \begin{cfa} 340 struct base_type { inline virtual_dtor; }; 341 struct intermediate_type { inline base_type; }; 342 struct derived_type { inline intermediate_type; }; 343 344 int main() { 345 derived_type d1, d2, d3; 346 intermediate_type & i = d2; 347 base_type & b = d3; 348 349 // these will call the destructors in the correct order 350 ^d1{}; ^i{}; ^b{}; 351 } 352 353 \end{cfa} 354 \caption{\CFA Virtual Destructor} 355 \label{f:VirtDtor} 356 \end{figure} 357 358 This virtual destructor system was built for this work, but is general and can be used in any type in \CFA. 359 Actors and messages opt into this system by inheriting the @virtual_dtor@ type, which allows the executor to call the right destructor without knowing the derived actor or message type. 360 361 Figure~\ref{f:ConvenienceMessages} shows three builtin convenience messages and receive routines used to terminate actors, depending on how an actor is allocated: @Delete@, @Destroy@ or @Finished@. 362 For example, in Figure~\ref{f:CFAActor}, the builtin @finished_msg@ message and receive are used to terminate the actor because the actor is allocated on the stack, so no deallocation actions are performed by the executor. 363 364 \begin{figure} 365 \begin{cfa} 366 message __base_msg_finished $@$= { .allocation_ : Finished }; // no auto-gen constructors 367 struct __delete_msg_t { inline message; } delete_msg = __base_msg_finished; 368 struct __destroy_msg_t { inline message; } destroy_msg = __base_msg_finished; 369 struct __finished_msg_t { inline message; } finished_msg = __base_msg_finished; 370 371 allocation receive( actor & this, __delete_msg_t & msg ) { return Delete; } 372 allocation receive( actor & this, __destroy_msg_t & msg ) { return Destroy; } 373 allocation receive( actor & this, __finished_msg_t & msg ) { return Finished; } 374 \end{cfa} 375 \caption{Builtin Convenience Messages} 376 \label{f:ConvenienceMessages} 377 \end{figure} 197 378 198 379 \section{\CFA Executor}\label{s:executor} 199 This section will describe the basic architecture of the \CFA executor. 200 Any discussion of work stealing is omitted until Section \ref{s:steal}. 201 The executor of an actor system is the scheduler that organizes where actors behaviours are run and how messages are sent and delivered. 202 In \CFA the executor lays out actors across the sharded message queues in round robin order as they are created. 203 The 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. 380 This section describes the basic architecture of the \CFA executor. 381 An executor of an actor system is the scheduler that organizes where actor behaviours are run and how messages are sent and delivered. 382 In \CFA, the executor is message-centric \see{Figure~\ref{f:inverted_actor}}, but extended by over sharding of a message queue \see{left side of Figure~\ref{f:gulp}}, \ie there are $M$ message queues where $M$ is greater than the number of executor threads $N$ (usually a multiple of $N$). 383 This approach reduces contention by spreading message delivery among the $M$ queues rather than $N$, while still maintaining actor FIFO message-delivery semantics. 384 The only extra overhead is each executor cycling (usually round-robin) through its $M$/$N$ queues. 385 The goal is to achieve better performance and scalability for certain kinds of actor applications by reducing executor locking. 386 Note, lock-free queues do not help because busy waiting on any atomic instruction is the source of the slowdown whether it is a lock or lock-free. 204 387 205 388 \begin{figure} … … 207 390 \input{diagrams/gulp.tikz} 208 391 \end{center} 209 \caption{ Diagram of the queue gulping mechanism.}392 \caption{Queue Gulping Mechanism} 210 393 \label{f:gulp} 211 394 \end{figure} 212 395 213 Each worker thread iterates over its own message queues until it finds one that contains messages. 214 At this point the worker thread \textbf{gulps} the queue. 215 A \textbf{gulp} is a term for consuming the contents of message queue and transferring them to the local queue of worker thread. 216 After the gulp is done atomically, this allows the worker thread to process the queue locally without any need for atomicity until the next gulp. 217 Messages can be added to the queue that was gulped in parallel with the processing of the local queue. 218 Additionally, prior to each gulp, the worker non-atomically checks if a queue is empty before attempting to gulp it. 219 Between this and the gulp, the worker avoids many potentially costly lock acquisitions. 220 An 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 222 To process its local queue, a worker thread takes each unit of work off the queue and executes it. 223 Since 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. 224 After running behaviour, the worker thread looks at the returned allocation status and takes the corresponding action. 225 Once all actors have marked themselves as being finished the executor initiates shutdown by inserting a sentinel value into the message queues. 226 Once a worker thread sees a sentinel it stops running. 227 After all workers stop running the actor system shutdown is complete. 228 229 \section{Envelopes}\label{s:envelope} 230 In actor systems messages are sent and received by actors. 231 When a actor receives a message it executes its behaviour that is associated with that message type. 232 However 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. 233 Furthermore 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. 234 All these requirements are fulfilled by a construct called an envelope. 235 The envelope wraps up the unit of work and also stores any information needed by data structures such as link fields. 236 To meet the persistence requirement the envelope is dynamically allocated and cleaned up after it has been delivered and its payload has run. 237 238 One may ask, "Could the link fields and other information be stored in the message?". 239 This is a good question to ask since messages also need to have a lifetime that persists beyond the work it delivers. 240 However, if one were to use messages as envelopes then a message would not be able to be sent to multiple actors at a time. 241 Therefore 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 243 This frequent allocation of envelopes with each message send between actors results in heavy contention on the memory allocator. 244 As such, a way to alleviate contention on the memory allocator could result in performance improvement. 245 Contention was reduced using a novel data structure that is called a copy queue. 246 247 \subsection{The Copy Queue}\label{s:copyQueue} 248 The copy queue is a thin layer over a dynamically sized array that is designed with the envelope use case in mind. 249 A copy queue supports the typical queue operations of push/pop but in a different way than a typical array based queue. 250 The copy queue is designed to take advantage of the \hyperref[s:executor]{gulping} pattern. 251 As such the amortized rutime cost of each push/pop operation for the copy queue is $O(1)$. 252 In 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. 253 Since 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. 254 As such, during pop operations there is no need to shift array elements. 255 An index is stored in the copy queue data structure which keeps track of which element to pop next allowing pop to be $O(1)$. 256 Push operations are amortized $O(1)$ since pushes may cause doubling reallocations of the underlying dynamic sized array. 396 Each executor thread iterates over its own message queues until it finds one with messages. 397 At this point, the executor thread atomically \gls{gulp}s the queue, meaning it moves the contents of message queue to a local queue of the executor thread using a single atomic instruction. 398 An example of the queue gulping operation is shown in the right side of Figure \ref{f:gulp}, where a executor threads gulps queue 0 and begins to process it locally. 399 This step allows an executor thread to process the local queue without any atomics until the next gulp. 400 Other executor threads can continue adding to the ends of executor thread's message queues. 401 In detail, an executor thread performs a test-and-gulp, non-atomically checking if a queue is non-empty, before attempting to gulp it. 402 If an executor misses an non-empty queue due to a race, it eventually finds the queue after cycling through its message queues. 403 This approach minimizes costly lock acquisitions. 404 405 Processing a local queue involves: removing a unit of work from the queue, dereferencing the actor pointed-to by the work-unit, running the actor's behaviour on the work-unit message, examining the returned allocation status from the @receive@ routine for the actor and internal status in the delivered message, and taking the appropriate actions. 406 Since all messages to a given actor are in the same queue, this guarantees atomicity across behaviours of that actor since it can only execute on one thread at a time. 407 As each actor is created or terminated by an executor thread, it increments/decrements a global counter. 408 When an executor decrements the counter to zero, it sets a global boolean variable that is checked by each executor thread when it has no work. 409 Once a executor threads sees the flag is set it stops running. 410 After all executors stop, the actor system shutdown is complete. 411 412 \subsection{Copy Queue}\label{s:copyQueue} 413 Unfortunately, the frequent allocation of envelopes for each send results in heavy contention on the memory allocator. 414 This contention is reduced using a novel data structure, called a \Newterm{copy queue}. 415 The copy queue is a thin layer over a dynamically sized array that is designed with the envelope use case in mind. 416 A copy queue supports the typical queue operations of push/pop but in a different way from a typical array-based queue. 417 418 The copy queue is designed to take advantage of the \gls{gulp}ing pattern, giving an amortized runtime cost for each push/pop operation of $O(1)$. 419 In contrast, a na\"ive array-based queue often has either push or pop cost $O(n)$ and the other cost $O(1)$ since one of the operations requires shifting the elements of the queue. 420 Since the executor threads gulp a queue to operate on it locally, this creates a usage pattern where all elements are popped from the copy queue without any interleaved pushes. 421 As such, during pop operations there is no need to shift array elements. 422 Instead, an index is stored in the copy-queue data-structure that keeps track of which element to pop next allowing pop to be $O(1)$. 423 Push operations are amortized $O(1)$ since pushes may cause doubling reallocations of the underlying dynamic-sized array (like \CC @vector@). 257 424 258 425 % C_TODO: maybe make copy_queue diagram 259 426 260 Since 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. 261 For 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. 262 One problem that arises with this approach is that this array based approach will often allocate more storage than what is needed. 263 Comparitively 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. 264 Additionally, 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 267 To mitigate this a memory reclamation scheme was introduced. 268 Initially the memory reclamation naively reclaimed one index of the array per gulp if the array size was above a low fixed threshold. 269 This approach had a problem. 270 The high memory usage watermark nearly doubled with this change! The issue with this approach can easily be highlighted with an example. 271 Say that there is a fixed throughput workload where a queue never has more than 19 messages at a time. 272 If the copy queue starts with a size of 10, it will end up doubling at some point to size 20 to accomodate 19 messages. 273 However, after 2 gulps and subsequent reclamations the array would be size 18. 274 The next time 19 messages are enqueued, the array size is doubled to 36! To avoid this issue a second check was added to reclamation. 275 Each copy queue started tracking the utilization of their array size. 276 Reclamation would only occur if less than half of the array was being utilized. 277 In 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. 278 However, the use of copy queues still incurs a higher memory cost than the list based queueing. 279 With 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}. 427 Since 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. 428 For many workload, the copy queues grow in size to facilitate the average number of messages in flight and there is no further dynamic allocations. 429 One downside of this approach that more storage is allocated than needed, \ie each copy queue is only partially full. 430 Comparatively, the individual envelope allocations of a list-based queue mean that the actor system always uses the minimum amount of heap space and cleans up eagerly. 431 Additionally, bursty workloads can cause the copy queues to allocate a large amounts of space to accommodate the peaks of the throughput, even if most of that storage is not needed for the rest of the workload's execution. 432 433 To mitigate memory wastage, a reclamation scheme is introduced. 434 Initially, the memory reclamation na\"ively reclaims one index of the array per \gls{gulp}, if the array size is above a low fixed threshold. 435 However, this approach has a problem. 436 The high memory watermark nearly doubled! 437 The issue is highlighted with an example. 438 Assume a fixed throughput workload, where a queue never has more than 19 messages at a time. 439 If the copy queue starts with a size of 10, it ends up doubling at some point to size 20 to accommodate 19 messages. 440 However, after 2 gulps and subsequent reclamations the array size is 18. 441 The next time 19 messages are enqueued, the array size is doubled to 36! 442 To avoid this issue, a second check is added. 443 Reclamation only occurs if less than half of the array is utilized. 444 This check achieves a lower total storage and overall memory utilization compared to the non-reclamation copy queues. 445 However, the use of copy queues still incurs a higher memory cost than list-based queueing, but the increase in memory usage is reasonable considering the performance gains \see{Section~\ref{s:actor_perf}}. 280 446 281 447 \section{Work Stealing}\label{s:steal} 282 Work stealing is a scheduling strategy t hat attempts to load balance, and increase resource untilization by having idle threads steal work.283 The re 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 448 Work stealing is a scheduling strategy to provide \Newterm{load balance}. 449 The goal is to increase resource utilization by having idle threads steal work from working threads. 450 While there are multiple parts in work-stealing scheduler, the two important components are victim selection and the stealing mechanism. 451 286 452 \subsection{Stealing Mechanism} 287 In 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}. 288 The stealing mechanism presented here differs from existing work stealing actor systems due the inverted actor system. 289 Other 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. 290 As an example, in CAF, the sharded actor queue is a set of double ended queues (dequeues). 291 Whenever an actor is moved to a ready queue, it is inserted into a worker's dequeue. 292 Workers then consume actors from the dequeue and execute their behaviours. 293 To steal work, thieves take one or more actors from a victim's dequeue. 294 This action creates contention on the dequeue, which can slow down the throughput of the victim. 295 The notion of which end of the dequeue is used for stealing, consuming, and inserting is not discussed since it isn't relevant. 296 By 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. 453 In work stealing, the stealing worker is called the \Newterm{thief} and the stolen-from worker is called the \Newterm{victim}. 454 The stealing mechanism presented here differs from existing work-stealing actor-systems because of the message-centric (inverted) actor-system. 455 Other actor systems, such as Akka~\cite{Akka} and CAF~\cite{CAF}, have work stealing, but use an actor-centric system where stealing is dequeuing from a non-empty ready-queue to an empty ready-queue. 456 As an example, in CAF, the sharded actor queue is a set of double-ended queues (dequeues). 457 When an actor has messages, it is inserted into a worker's dequeue (ready queue). 458 Workers then consume actors from the dequeue and execute their behaviours. 459 To steal work, thieves take one or more actors from a victim's dequeue. 460 By 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 in a dequeue-based system always results in a potential increase in contention on the dequeues. 461 This contention can slows down the victim's throughput. 462 Note, which end of the dequeue is used for stealing, consuming, and inserting is not discussed since the largest cost is the mutual exclusion and its duration for safely performing the queue operations. 463 464 Work steal now becomes queue stealing, where an entire actor/message queue is stolen, which trivially preserves message ordering in a queue \see{Section~\ref{s:steal}}. 297 465 298 466 % C_TODO: maybe insert stealing diagram 299 467 300 In \CFA, the actor work stealing implementation is unique. 301 While other systems are concerned with stealing actors, the \CFA actor system steals queues. 302 This is a result of \CFA's use of the inverted actor system. 303 The goal of the \CFA actor work stealing mechanism is to have a zero-victim-cost stealing mechanism. 304 This does not means that stealing has no cost. 305 This goal is to ensure that stealing work does not impact the performance of victim workers. 306 This means that thieves can not contend with victims, and that victims should perform no stealing related work unless they become a thief. 307 In theory this goal is not achieved, but results will be presented that show the goal is achieved in practice. 308 In \CFA's actor system workers own a set of sharded queues which they iterate over and gulp. 309 If a worker has iterated over the queues they own twice without finding any work, they try to steal a queue from another worker. 310 Stealing a queue is done wait-free with a few atomic instructions that can only create contention with other stealing workers. 311 To steal a queue a worker does the following: 468 In \CFA, the actor work-stealing implementation is unique because of the message-centric system. 469 In this system, it is impractical to steal actors because an actor's messages are distributed in temporal order along the message queue. 470 To ensure sequential actor execution and FIFO message delivery, actor stealing requires finding and removing all of an actor's messages, and inserting them consecutively in another message queue. 471 This operation is $O(N)$ with a non-trivial constant. 472 The only way for work stealing to become practical is to shard the message queue, which also reduces contention, and steal queues to eliminate queue searching. 473 474 Given queue stealing, the goal is to have a zero-victim-cost stealing mechanism, which does not mean stealing has no cost. 475 It means work stealing does not affect the performance of the victim worker. 476 The implication is that thieves cannot contend with a victim, and that a victim should perform no stealing related work unless it becomes a thief. 477 In theory, this goal is not achievable, but results show the goal is achieved in practice. 478 479 In \CFA's actor system, workers own a set of sharded queues, which they iterate over and gulp. 480 If a worker has iterated over its message queues twice without finding any work, it tries to steal a queue from another worker. 481 Stealing a queue is done wait-free with a few atomic instructions that can only create contention with other stealing workers, not the victim. 482 To steal a queue, a worker does the following: 312 483 \begin{enumerate}[topsep=5pt,itemsep=3pt,parsep=0pt] 313 484 \item 314 The thief chooses a victim. 315 316 \item 317 The thief starts at a random index in the array of the victim's queues and searches for a candidate queue. 318 A candidate queue is any queue that is not empty, is not being stolen by another thief, and is not being processed by the victim. 319 These are not strictly enforced rules. 320 The candidate is identified non-atomically and as such queues that do not satisfy these rules may be stolen. 321 However, 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 325 Once 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. 326 This swap can fail. 327 If the swap is successful the thief swaps the two queues. 328 If the swap fails, another thief must have attempted to steal one of the two queues being swapped. 329 Failing to steal is good in this case since stealing a queue that was just swapped would likely result in stealing an empty queue. 485 The thief chooses a victim, which is trivial because all workers are stored in a shared array. 486 487 \item 488 The thief starts at a random index in the array of the victim's queues and searches for a candidate queue. 489 A candidate queue is any non-empty queue not being processed by the victim and not being stolen by another thief. 490 These rules are not strictly enforced. 491 A candidate is identified non-atomically, and as such, queues that do not satisfy these rules may be stolen. 492 However, steals not meeting the rules do not affect correctness and do not constitute failed steals as the queue is always swapped. 493 494 \item 495 Once a candidate queue is chosen, the thief attempts a wait-free swap of a victim's queue to a random empty thief queue. 496 If the swap successes, the steal is completed. 497 If the swap fails, the victim may have been gulping that message queue or another thief must have attempted to steal the victim's queue. 498 In either case, that message queue is highly likely to be empty. 499 500 \item 501 Once a thief fails or succeeds in stealing a queue, it iterates over its messages queues again because new messages may have arrived during stealing. 502 Stealing is only repeated after two consecutive iterations over its owned queues without finding work. 330 503 \end{enumerate} 331 504 332 Once a thief fails or succeeds in stealing a queue, it goes back to its own set of queues and iterates over them again. 333 It will only try to steal again once it has completed two consecutive iterations over its owned queues without finding any work. 334 The key to the stealing mechnism is that the queues can still be operated on while they are being swapped. 335 This elimates any contention between thieves and victims. 336 The first key to this is that actors and workers maintain two distinct arrays of references to queues. 337 Actors will always receive messages via the same queues. 338 Workers, 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. 339 Swapping queues is a matter of atomically swapping two pointers in the worker array. 505 The key to the stealing mechanism is that the queues can still be operated on while they are being swapped. 506 This functionality eliminates any contention among thieves and victims. 507 508 The first key to this is that actors and workers maintain two distinct arrays of references to queues. 509 Actors will always receive messages via the same queues. 510 Workers, 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. 511 Swapping queues is a matter of atomically swapping two pointers in the worker array. 340 512 As such pushes to the queues can happen concurrently during the swap since pushes happen via the actor queue references. 341 513 342 Gulping can also occur during queue swapping, but the implementation requires more nuance than the pushes. 343 When a worker is not stealing it iterates across its own range of queues and gulps them one by one. 344 When a worker operates on a queue it first copies the current pointer from the worker array of references to a local variable. 345 It then uses that local variable for all queue operations until it moves to the next index of its range of the queue array. 346 This ensures that any swaps do not interrupt gulping operations, however this introduces a correctness issue. 347 If any behaviours from a queue are run by two workers at a time it violates both mutual exclusion and the actor ordering guarantees. 348 As such this must be avoided. 349 To avoid this each queue has a \code{being_processed} flag that is atomically set to \code{true} when a queue is gulped.350 The flag indicates that a queue is being processed locally and is set back to \code{false} once the local processing is finished.351 If 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.352 This 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.353 However, the window for this race is very small, making this contention rare. 354 This is why the claim is made that this mechanism is zero-victim-cost in practice but not in theory. 355 By 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.514 Gulping can also occur during queue swapping, but the implementation requires more nuance than the pushes. 515 When a worker is not stealing it iterates across its own range of queues and gulps them one by one. 516 When a worker operates on a queue it first copies the current pointer from the worker array of references to a local variable. 517 It then uses that local variable for all queue operations until it moves to the next index of its range of the queue array. 518 This ensures that any swaps do not interrupt gulping operations, however this introduces a correctness issue. 519 If any behaviours from a queue are run by two workers at a time it violates both mutual exclusion and the actor ordering guarantees. 520 As such this must be avoided. 521 To avoid this each queue has a @being_processed@ flag that is atomically set to @true@ when a queue is gulped. 522 The flag indicates that a queue is being processed locally and is set back to @false@ once the local processing is finished. 523 If a worker attempts to gulp a queue and finds that the @being_processed@ flag is @true@, it does not gulp the queue and moves on to the next queue in its range. 524 This is a source of contention between victims and thieves since a thief may steal a queue and set @being_processed@ to @true@ between a victim saving a pointer to a queue and gulping it. 525 However, the window for this race is very small, making this contention rare. 526 This is why the claim is made that this mechanism is zero-victim-cost in practice but not in theory. 527 By collecting statistics on failed gulps due to the @being_processed@ flag, it is found that this contention occurs ~0.05\% of the time when a gulp occurs. 356 528 Hence, the claim is made that this stealing mechanism has zero-victim-cost in practice. 357 529 358 530 359 531 \subsection{Queue Swap Correctness} 360 Given the wait-free swap used is novel, it is important to show that it is correct. 361 Firstly, 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. 362 There 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. 363 In both cases it is apropos for a thief to given up on stealing. 364 \CFA-style pseudocode for the queue swap is presented below. 365 The swap uses compare-and-swap ( \code{CAS}) which is just pseudocode for C's \code{__atomic_compare_exchange_n}.366 A pseudocode implementation of \code{CAS} is also shown below.367 The correctness of the wait-free swap will now be discussed in detail. 532 Given the wait-free swap used is novel, it is important to show that it is correct. 533 Firstly, 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. 534 There 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. 535 In both cases it is apropos for a thief to given up on stealing. 536 \CFA-style pseudocode for the queue swap is presented below. 537 The swap uses compare-and-swap (@CAS@) which is just pseudocode for C's @__atomic_compare_exchange_n@. 538 A pseudocode implementation of @CAS@ is also shown below. 539 The correctness of the wait-free swap will now be discussed in detail. 368 540 To first verify sequential correctness, consider the equivalent sequential swap below: 369 541 … … 382 554 \end{cfa} 383 555 384 Step 1 is missing in the sequential example since in only matter in the concurrent context presented later. 385 By looking at the sequential swap it is easy to see that it is correct. 556 Step 1 is missing in the sequential example since in only matter in the concurrent context presented later. 557 By looking at the sequential swap it is easy to see that it is correct. 386 558 Temporary 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 559 … … 403 575 // Step 1: 404 576 // If either queue is 0p then they are in the process of being stolen 405 // 0p is C ForAll's equivalent of C++'s nullptr577 // 0p is Cforall's equivalent of C++'s nullptr 406 578 if ( vic_queue == 0p ) return false; 407 579 … … 411 583 if ( !CAS( &request_queues[my_idx], &my_queue, 0p ) ) 412 584 return false; 413 585 414 586 // Step 3: 415 587 // Try to set victim queue ptr to be thief's queue ptr. … … 434 606 Step 0 is the same as the sequential example, and the thief stores local copies of the two pointers to be swapped. 435 607 \item 436 Step 1 verifies that the stored copy of the victim queue pointer, \code{vic_queue}, is valid.437 If \code{vic_queue} is equal to \code{0p}, then the victim queue is part of another swap so the operation fails.438 No state has changed at this point so no fixups are needed. 439 Note, \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.440 At no other point will a queue pointer be set to \code{0p}.441 Since each worker owns a disjoint range of the queue array, it is impossible for \code{my_queue} to be \code{0p}.442 \item 443 Step 2 attempts to set the thief's queue pointer to \code{0p} via \code{CAS}.444 The \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.445 At this point the thief-turned-victim will fail and since it has not changed any state it just fails and returns false. 446 If the \code{CAS} succeeds then the thief's queue pointer will now be \code{0p}.447 Nulling 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 449 Step 3 attempts to set the victim's queue pointer to be \code{my_queue} via \code{CAS}.450 If the \code{CAS} succeeds then the victim's queue pointer has been set and swap can no longer fail.451 If the \code{CAS}fails then the thief's queue pointer must be restored to its previous value before returning.452 \item 453 Step 4 sets the thief's queue pointer to be \code{vic_queue}completing the swap.608 Step 1 verifies that the stored copy of the victim queue pointer, @vic_queue@, is valid. 609 If @vic_queue@ is equal to @0p@, then the victim queue is part of another swap so the operation fails. 610 No state has changed at this point so no fixups are needed. 611 Note, @my_queue@ can never be equal to @0p@ at this point since thieves only set their own queues pointers to @0p@ when stealing. 612 At no other point will a queue pointer be set to @0p@. 613 Since each worker owns a disjoint range of the queue array, it is impossible for @my_queue@ to be @0p@. 614 \item 615 Step 2 attempts to set the thief's queue pointer to @0p@ via @CAS@. 616 The @CAS@ will only fail if the thief's queue pointer is no longer equal to @my_queue@, which implies that this thief has become a victim and its queue has been stolen. 617 At this point the thief-turned-victim will fail and since it has not changed any state it just fails and returns false. 618 If the @CAS@ succeeds then the thief's queue pointer will now be @0p@. 619 Nulling 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 @0p@. 620 \item 621 Step 3 attempts to set the victim's queue pointer to be @my_queue@ via @CAS@. 622 If the @CAS@ succeeds then the victim's queue pointer has been set and swap can no longer fail. 623 If the @CAS@ fails then the thief's queue pointer must be restored to its previous value before returning. 624 \item 625 Step 4 sets the thief's queue pointer to be @vic_queue@ completing the swap. 454 626 \end{enumerate} 455 627 … … 458 630 \end{theorem} 459 631 460 Correctness of the swap is shown through the existence of an invariant. 461 The 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.462 To show that this invariant holds, it is shown that it is true at each step of the swap. 463 Step 0 and 1 do not write and as such they cannot invalidate the invariant of any other thieves. 464 In step 2 a thief attempts to write \code{0p} to one of their queue pointers.465 This queue pointer cannot be \code{0p}.466 As 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.467 As 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. 468 In step 3 the thief attempts to write \code{my_queue} to the victim's queue pointer.469 If 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.470 Therefore in the success case where the \code{CAS} succeeds, the value of the victim's queue pointer must not be \code{0p}.471 As such, the write will never overwrite a value of \code{0p}, hence the invariant is held in the \code{CAS} of step 3.472 The 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 474 Given this informal proof of invariance it can be shown that the successful swap is correct. 475 Once a thief atomically sets their queue pointer to be \code{0p} in step 2, the invariant guarantees that pointer will not change.476 As 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}.477 Given 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. 478 By the invariant the write back in the successful case is correct since no other worker can write to the \code{0p}pointer.479 480 In the failed case the outcome is correct in steps 1 and 2 since no writes have occur ed so the program state is unchanged.481 In 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.632 Correctness of the swap is shown through the existence of an invariant. 633 The invariant is that when a queue pointer is set to @0p@ by a thief, then the next write to the pointer can only be performed by the same thief. 634 To show that this invariant holds, it is shown that it is true at each step of the swap. 635 Step 0 and 1 do not write and as such they cannot invalidate the invariant of any other thieves. 636 In step 2 a thief attempts to write @0p@ to one of their queue pointers. 637 This queue pointer cannot be @0p@. 638 As stated above, @my_queue@ is never equal to @0p@ since thieves will only write @0p@ to queue pointers from their own queue range and all worker's queue ranges are disjoint. 639 As 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. 640 In step 3 the thief attempts to write @my_queue@ to the victim's queue pointer. 641 If the current value of the victim's queue pointer is @0p@, then the CAS will fail since @vic_queue@ cannot be equal to @0p@ because of the check in step 1. 642 Therefore in the success case where the @CAS@ succeeds, the value of the victim's queue pointer must not be @0p@. 643 As such, the write will never overwrite a value of @0p@, hence the invariant is held in the @CAS@ of step 3. 644 The 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 @0p@ queue pointer and they are being set by the same thief that set the pointer to @0p@. 645 646 Given this informal proof of invariance it can be shown that the successful swap is correct. 647 Once a thief atomically sets their queue pointer to be @0p@ in step 2, the invariant guarantees that pointer will not change. 648 As such, in the success case step 3 it is known that the value of the victim's queue pointer that was overwritten must be @vic_queue@ due to the use of @CAS@. 649 Given 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. 650 By the invariant the write back in the successful case is correct since no other worker can write to the @0p@ pointer. 651 652 In the failed case the outcome is correct in steps 1 and 2 since no writes have occurred so the program state is unchanged. 653 In the failed case of step 3 the program state is safely restored to its state it had prior to the @0p@ write in step 2, thanks to the invariant that makes the write back to the @0p@ pointer safe. 482 654 483 655 \subsection{Stealing Guarantees} 484 485 % C_TODO insert graphs for each proof 486 Given that the stealing operation can potentially fail, it is important to discuss the guarantees provided by the stealing implementation. 487 Given 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. 488 Since each thief can only steal from one victim at a time, each vertex can only have at most one outgoing edge. 656 Given that the stealing operation can potentially fail, it is important to discuss the guarantees provided by the stealing implementation. 657 Given 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. 658 Since each thief can only steal from one victim at a time, each vertex can only have at most one outgoing edge. 489 659 A 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 660 … … 498 668 499 669 \begin{theorem} 500 Given $M$ thieves queues all attempting to swap with one victim queue, and no other swaps occur ing that involve these queues, at least one swap is guaranteed to succeed.670 Given $M$ thieves queues all attempting to swap with one victim queue, and no other swaps occurring that involve these queues, at least one swap is guaranteed to succeed. 501 671 \end{theorem}\label{t:one_vic} 502 672 A graph of the $M$ thieves swapping with one victim discussed in this theorem is presented in Figure~\ref{f:M_one_swap}. 503 673 \\ 504 First it is important to state that a thief will not attempt to steal from themselves. 505 As such, the victim here is not also a thief. 506 Stepping 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}.507 Similarly for all thieves step 2 will succeed since no one is stealing from any of the thieves. 508 In step 3 the first thief to \code{CAS} will win the race and successfully swap the queue pointer.509 Since 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.674 First it is important to state that a thief will not attempt to steal from themselves. 675 As such, the victim here is not also a thief. 676 Stepping 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 @0p@. 677 Similarly for all thieves step 2 will succeed since no one is stealing from any of the thieves. 678 In step 3 the first thief to @CAS@ will win the race and successfully swap the queue pointer. 679 Since it is the first one to @CAS@ and @CAS@ is atomic, there is no way for the @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. 510 680 Hence at least one swap is guaranteed to succeed in this case. 511 681 … … 519 689 520 690 \begin{theorem} 521 Given $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 occur ing that involve these queues, at least one swap is guaranteed to succeed.691 Given $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 occurring that involve these queues, at least one swap is guaranteed to succeed. 522 692 \end{theorem}\label{t:vic_chain} 523 693 A graph of the chain of swaps discussed in this theorem is presented in Figure~\ref{f:chain_swap}. 524 694 \\ 525 This is a proof by contradiction. 526 Assume no swaps occur. 527 Then all thieves must have failed at step 1, step 2 or step 3. 528 For a given thief $b$ to fail at step 1, thief $b + 1$ must have succe ded at step 2 before $b$ executes step 0.529 Hence, not all thieves can fail at step 1. 530 Furthermore 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. 531 There 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. 695 This is a proof by contradiction. 696 Assume no swaps occur. 697 Then all thieves must have failed at step 1, step 2 or step 3. 698 For a given thief $b$ to fail at step 1, thief $b + 1$ must have succeeded at step 2 before $b$ executes step 0. 699 Hence, not all thieves can fail at step 1. 700 Furthermore 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. 701 There 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. 532 702 Hence, without loss of generality, whether thieves succeed or fail at step 1, this proof can proceed inductively. 533 703 534 For 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. 535 The 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. 536 If $j$ finished step 3 then the at least one swap was successful. 537 Therefore all thieves did not fail at step 2. 538 Hence all thieves must successfully complete step 2 and fail at step 3. 539 However, 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. 540 Hence, in this case thief $1$ will always succeed in step 3 if all thieves succeed in step 2. 704 For 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. 705 The 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. 706 If $j$ finished step 3 then the at least one swap was successful. 707 Therefore all thieves did not fail at step 2. 708 Hence all thieves must successfully complete step 2 and fail at step 3. 709 However, 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. 710 Hence, in this case thief $1$ will always succeed in step 3 if all thieves succeed in step 2. 541 711 Thus, by contradiction with the earlier assumption that no swaps occur, at least one swap must succeed. 542 712 … … 545 715 \centering 546 716 \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}} 717 \subfloat[Cyclic Swap Graph]{\label{f:cyclic_swap}\input{diagrams/cyclic_swap.tikz}} & 718 \subfloat[Acyclic Swap Graph]{\label{f:acyclic_swap}\input{diagrams/acyclic_swap.tikz}} 549 719 \end{tabular} 550 720 \caption{Illustrations of cyclic and acyclic swap graphs.} … … 552 722 553 723 \begin{theorem} 554 Given a set of $M > 1$ swaps occur ing that form a single directed connected graph.555 At least one swap is guaranteed to suc eed if and only if the graph does not contain a cycle.724 Given a set of $M > 1$ swaps occurring that form a single directed connected graph. 725 At least one swap is guaranteed to succeed if and only if the graph does not contain a cycle. 556 726 \end{theorem}\label{t:vic_cycle} 557 Representations of cyclic and acy lic swap graphs discussed in this theorem are presented in Figures~\ref{f:cyclic_swap} and \ref{f:acyclic_swap}.727 Representations of cyclic and acyclic swap graphs discussed in this theorem are presented in Figures~\ref{f:cyclic_swap} and \ref{f:acyclic_swap}. 558 728 \\ 559 First the reverse direction is proven. 560 If the graph does not contain a cycle, then there must be at least one successful swap. 561 Since the graph contains no cycles and is finite in size, then there must be a vertex $A$ with no outgoing edges. 562 The 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. 563 The forward direction is proven by contradiction in a similar fashion to \ref{t:vic_chain}. 564 Assume no swaps occur. 565 Similar 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. 566 Similar 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. 567 Hence, the only way forward is to assume all thieves successfully complete step 2. 568 Hence for there to be no swaps all thieves must fail step 3. 569 However, 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$. 570 Since 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. 729 First the reverse direction is proven. 730 If the graph does not contain a cycle, then there must be at least one successful swap. 731 Since the graph contains no cycles and is finite in size, then there must be a vertex $A$ with no outgoing edges. 732 The 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. 733 The forward direction is proven by contradiction in a similar fashion to \ref{t:vic_chain}. 734 Assume no swaps occur. 735 Similar 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. 736 Similar 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. 737 Hence, the only way forward is to assume all thieves successfully complete step 2. 738 Hence for there to be no swaps all thieves must fail step 3. 739 However, 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$. 740 Since 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. 571 741 Thus, 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 742 573 The forward direction is proven by contrapositive. 574 If the graph contains a cycle then there exists a situation where no swaps occur. 575 This situation is constructed. 576 Since all vertices have at most one outgoing edge the cycle must be directed. 577 Furthermore, since the graph contains a cycle all vertices in the graph must have exactly one outgoing edge. 578 This is shown through construction of an ar ibtrary cyclic graph.579 The graph contains a directed cycle by definition, so the construction starts with $T$ vertices in a directed cycle. 580 Since 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 accom odate new vertices with no outgoing edges.581 Any vertices added to the graph must have an outgoing edge to connect, leaving the resulting graph with no available outgoing edges. 582 Thus, by induction all vertices in the graph must have exactly one outgoing edge. 583 Hence all vertices are thief queues. 584 Now consider the case where all thieves successfully complete step 0-1, and then they all complete step 2. 585 At this point all thieves are attempting to swap with a queue pointer whose value has changed to \code{0p}.586 If all thieves attempt the \code{CAS} before any write backs, then they will all fail.587 Thus, by contrapositive, if the graph contains a cycle then there exists a situation where no swaps occur. 588 Hence, at least one swap is guaranteed to suc eed if and only if the graph does not contain a cycle.743 The forward direction is proven by contrapositive. 744 If the graph contains a cycle then there exists a situation where no swaps occur. 745 This situation is constructed. 746 Since all vertices have at most one outgoing edge the cycle must be directed. 747 Furthermore, since the graph contains a cycle all vertices in the graph must have exactly one outgoing edge. 748 This is shown through construction of an arbitrary cyclic graph. 749 The graph contains a directed cycle by definition, so the construction starts with $T$ vertices in a directed cycle. 750 Since 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 accommodate new vertices with no outgoing edges. 751 Any vertices added to the graph must have an outgoing edge to connect, leaving the resulting graph with no available outgoing edges. 752 Thus, by induction all vertices in the graph must have exactly one outgoing edge. 753 Hence all vertices are thief queues. 754 Now consider the case where all thieves successfully complete step 0-1, and then they all complete step 2. 755 At this point all thieves are attempting to swap with a queue pointer whose value has changed to @0p@. 756 If all thieves attempt the @CAS@ before any write backs, then they will all fail. 757 Thus, by contrapositive, if the graph contains a cycle then there exists a situation where no swaps occur. 758 Hence, at least one swap is guaranteed to succeed if and only if the graph does not contain a cycle. 589 759 590 760 % C_TODO: go through and use \paragraph to format to make it look nicer 591 761 \subsection{Victim Selection}\label{s:victimSelect} 592 In any work stealing algorithm thieves have some heuristic to determine which victim to choose from. 593 Choosing this algorithm is difficult and can have implications on performance. 594 There is no one selection heuristic that is known to be the best on all workloads. 595 Recent work focuses on locality aware scheduling in actor systems\cite{barghi18}\cite{wolke17}. 596 However, while locality aware scheduling provides good performance on some workloads, something as simple as randomized selection performs better on other workloads\cite{barghi18}. 597 Since locality aware scheduling has been explored recently, this work introduces a heuristic called \textbf{longest victim} and compares it to randomized work stealing. 598 The longest victim heuristic maintains a timestamp per worker thread that is updated every time a worker attempts to steal work.599 Thieves then attempt to steal from the thread with the oldest timestamp. 600 This means that if two thieves look to steal at the same time, they likely will attempt to steal from the same victim. 601 This 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. 602 Furthermore 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}. 603 Addit onally, the longest victim heuristic makes it very improbable that the no swap scenario presented in Theorem \ref{t:vic_cycle} manifests.604 Given the longest victim heuristic, for a cycle to manifest it would require all workers to attempt to steal in a short timeframe. 605 This 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. 762 In any work stealing algorithm thieves have some heuristic to determine which victim to choose from. 763 Choosing this algorithm is difficult and can have implications on performance. 764 There is no one selection heuristic that is known to be the best on all workloads. 765 Recent work focuses on locality aware scheduling in actor systems\cite{barghi18}\cite{wolke17}. 766 However, while locality aware scheduling provides good performance on some workloads, something as simple as randomized selection performs better on other workloads\cite{barghi18}. 767 Since locality aware scheduling has been explored recently, this work introduces a heuristic called \textbf{longest victim} and compares it to randomized work stealing. 768 The longest victim heuristic maintains a timestamp per executor threads that is updated every time a worker attempts to steal work. 769 Thieves then attempt to steal from the thread with the oldest timestamp. 770 This means that if two thieves look to steal at the same time, they likely will attempt to steal from the same victim. 771 This 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. 772 Furthermore 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}. 773 Additionally, the longest victim heuristic makes it very improbable that the no swap scenario presented in Theorem \ref{t:vic_cycle} manifests. 774 Given the longest victim heuristic, for a cycle to manifest it would require all workers to attempt to steal in a short timeframe. 775 This 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. 606 776 In 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 777 608 \section{Safety and Productivity} 609 \CFA's actor system comes with a suite of safety and productivity features. 610 Most of these features are present in \CFA's debug mode, but are removed when code is compiled in nodebug mode. 778 \section{Safety and Productivity}\label{s:SafetyProductivity} 779 \CFA's actor system comes with a suite of safety and productivity features. 780 Most of these features are present in \CFA's debug mode, but are removed when code is compiled in nodebug mode. 611 781 The suit of features include the following. 612 782 613 783 \begin{itemize} 614 \item Static-typed message sends. 784 \item Static-typed message sends. 615 785 If 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. 617 All actors have a ticket that assigns them to a respective queue. 786 \item Detection of message sends to Finished/Destroyed/Deleted actors. 787 All actors have a ticket that assigns them to a respective queue. 618 788 The 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. 789 \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. 620 790 As 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.622 If there are fewer queues than worker threads, then some workers will spin and never do any work.623 There 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. 625 Since the \code{Finished} allocation status is unused for messages, it is used internally to detect if a message has been sent.791 \item When an executor is created, the queues are handed out to executor threads in round robin order. 792 If there are fewer queues than executor threads, then some workers will spin and never do any work. 793 There is no reasonable use case for this behaviour so an error is printed if the number of queues is fewer than the number of executor threads. 794 \item A warning is printed when messages are deallocated without being sent. 795 Since the @Finished@ allocation status is unused for messages, it is used internally to detect if a message has been sent. 626 796 Deallocating 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. 797 \item Detection of messages sent but not received 798 As discussed in Section~\ref{s:executor}, once all actors have terminated shutdown is communicated to executor threads via a status flag. Upon termination the executor threads check their queues to see if any contain messages. If they do, an error is reported. Messages being sent but not received means that their allocation action did not occur and their payload was not delivered. Missing the allocation action can lead to memory leaks and missed payloads can cause unpredictable behaviour. Detecting this can indicate a race or logic error in the user's code. 627 799 \end{itemize} 628 800 629 In addition to these features, \CFA's actor system comes with a suite of statistics that can be toggled on and off. 630 These statistics have minimal impact on the actor system's performance since they are counted on a per worker thread basis.631 During shutdown of the actor system they are aggregated, ensuring that the only atomic instructions used by the statistics counting happen at shutdown. 801 In addition to these features, \CFA's actor system comes with a suite of statistics that can be toggled on and off. 802 These statistics have minimal impact on the actor system's performance since they are counted on a per executor threads basis. 803 During shutdown of the actor system they are aggregated, ensuring that the only atomic instructions used by the statistics counting happen at shutdown. 632 804 The statistics measured are as follows. 633 805 634 806 \begin{description} 635 807 \item[\LstBasicStyle{\textbf{Actors Created}}] 636 Actors created. 808 Actors created. 637 809 Includes both actors made by the main and ones made by other actors. 638 810 \item[\LstBasicStyle{\textbf{Messages Sent}}] 639 Messages sent and received. 640 Includes termination messages send to the worker threads.811 Messages sent and received. 812 Includes termination messages send to the executor threads. 641 813 \item[\LstBasicStyle{\textbf{Gulps}}] 642 Gulps that occur ed across the worker threads.814 Gulps that occurred across the executor threads. 643 815 \item[\LstBasicStyle{\textbf{Average Gulp Size}}] 644 816 Average number of messages in a gulped queue. 645 817 \item[\LstBasicStyle{\textbf{Missed gulps}}] 646 Occur ences where a worker missed a gulp due to the concurrent queue processing by another worker.818 Occurrences where a worker missed a gulp due to the concurrent queue processing by another worker. 647 819 \item[\LstBasicStyle{\textbf{Steal attempts}}] 648 Worker threads attempts to steal work. 820 Worker threads attempts to steal work. 649 821 650 822 \item[\LstBasicStyle{\textbf{Steal failures (no candidates)}}] … … 658 830 \end{description} 659 831 660 These 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. 661 For 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.832 These 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. 833 For 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 executor threads. 662 834 In another example, if the average gulp size is very high, it could indicate that the executor could use more queue sharding. 663 835 664 836 % C_TODO cite poison pill messages and add languages 665 Another productivity feature that is included is a group of poison-pill messages. 666 Poison-pill messages are common across actor systems, including Akka and ProtoActor \cite{}. 667 Poison-pill messages inform an actor to terminate. 668 In \CFA, due to the allocation of actors and lack of garbage collection, there needs to be a suite of poison-pills. 669 The messages that \CFA provides are \code{DeleteMsg}, \code{DestroyMsg}, and \code{FinishedMsg}.670 These 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. 671 Note that any pending messages to the actor will still be sent. 837 Another productivity feature that is included is a group of poison-pill messages. 838 Poison-pill messages are common across actor systems, including Akka and ProtoActor \cite{}. 839 Poison-pill messages inform an actor to terminate. 840 In \CFA, due to the allocation of actors and lack of garbage collection, there needs to be a suite of poison-pills. 841 The messages that \CFA provides are @DeleteMsg@, @DestroyMsg@, and @FinishedMsg@. 842 These 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. 843 Note that any pending messages to the actor will still be sent. 672 844 It is still the user's responsibility to ensure that an actor does not receive any messages after termination. 673 845 … … 675 847 \CAP{I will update the figures to have the larger font size and different line markers once we start editing this chapter.} 676 848 The performance of \CFA's actor system is tested using a suite of microbenchmarks, and compared with other actor systems. 677 Most of the benchmarks are the same as those presented in \ref{}, with a few additions. 849 Most of the benchmarks are the same as those presented in \ref{}, with a few additions. 678 850 % C_TODO cite actor paper 679 At 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. 851 At the time of this work the versions of the actor systems are as follows. 852 \CFA 1.0, \uC 7.0.0, Akka Typed 2.7.0, CAF 0.18.6, and ProtoActor-Go v0.0.0-20220528090104-f567b547ea07. 681 853 Akka Classic is omitted as Akka Typed is their newest version and seems to be the direction they are headed in. 682 854 The experiments are run on … … 688 860 \end{list} 689 861 690 The benchmarks are run on up to 48 cores. 691 On the Intel, when going beyond 24 cores there is the choice to either hop sockets or to use hyperthreads. 692 Either choice will cause a blip in performance trends, which can be seen in the following performance figures. 862 The benchmarks are run on up to 48 cores. 863 On the Intel, when going beyond 24 cores there is the choice to either hop sockets or to use hyperthreads. 864 Either choice will cause a blip in performance trends, which can be seen in the following performance figures. 693 865 On the Intel the choice was made to hyperthread instead of hopping sockets for experiments with more than 24 cores. 694 866 695 All benchmarks presented are run 5 times and the median is taken. 696 Error bars showing the 95\% confidence intervals are drawn on each point on the graphs. 697 If the confidence bars are small enough, they may be obscured by the point. 698 In this section \uC will be compared to \CFA frequently, as the actor system in \CFA was heavily based off \uC's actor system. 699 As such the pe formance differences that arise are largely due to the contributions of this work.867 All benchmarks presented are run 5 times and the median is taken. 868 Error bars showing the 95\% confidence intervals are drawn on each point on the graphs. 869 If the confidence bars are small enough, they may be obscured by the point. 870 In this section \uC will be compared to \CFA frequently, as the actor system in \CFA was heavily based off \uC's actor system. 871 As such the performance differences that arise are largely due to the contributions of this work. 700 872 701 873 \begin{table}[t] … … 708 880 \begin{tabular}{*{5}{r|}r} 709 881 & \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 882 \hline 711 883 AMD & \input{data/pykeSendStatic} \\ 712 \hline 884 \hline 713 885 Intel & \input{data/nasusSendStatic} 714 886 \end{tabular} … … 721 893 \begin{tabular}{*{5}{r|}r} 722 894 & \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 895 \hline 724 896 AMD & \input{data/pykeSendDynamic} \\ 725 \hline 897 \hline 726 898 Intel & \input{data/nasusSendDynamic} 727 899 \end{tabular} … … 729 901 730 902 \subsection{Message Sends} 731 Message sending is the key component of actor communication. 732 As such latency of a single message send is the fundamental unit of fast-path performance for an actor system. 733 The following two microbenchmarks evaluate the average latency for a static actor/message send and a dynamic actor/message send. 734 Static and dynamic refer to the allocation of the message and actor. 735 In 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. 736 The average latency per message send is then calculated by dividing the duration by the number of sends. 737 This 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. 903 Message sending is the key component of actor communication. 904 As such latency of a single message send is the fundamental unit of fast-path performance for an actor system. 905 The following two microbenchmarks evaluate the average latency for a static actor/message send and a dynamic actor/message send. 906 Static and dynamic refer to the allocation of the message and actor. 907 In 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. 908 The average latency per message send is then calculated by dividing the duration by the number of sends. 909 This 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. 738 910 The CAF static send benchmark only sends a message 10M times to avoid extensively long run times. 739 911 740 In the dynamic send benchmark the same experiment is performed, with the change that with each send a new actor and message is allocated. 741 This 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. 912 In the dynamic send benchmark the same experiment is performed, with the change that with each send a new actor and message is allocated. 913 This 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. 742 914 Since 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 915 744 The 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. 746 In the static send benchmark all systems except CAF have static send costs that are in the same ballpark, only varying by ~70ns. 747 In the dynamic send benchmark all systems experience slower message sends, as expected due to the extra allocations. 748 However, Akka and ProtoActor, slow down by a more significant margin than the \uC and \CFA. 916 The results from the static/dynamic send benchmarks are shown in Figures~\ref{t:StaticActorMessagePerformance} and \ref{t:DynamicActorMessagePerformance} respectively. 917 \CFA leads the charts in both benchmarks, largely due to the copy queue removing the majority of the envelope allocations. 918 In the static send benchmark all systems except CAF have static send costs that are in the same ballpark, only varying by ~70ns. 919 In the dynamic send benchmark all systems experience slower message sends, as expected due to the extra allocations. 920 However, Akka and ProtoActor, slow down by a more significant margin than the \uC and \CFA. 749 921 This 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 922 751 923 \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}. 924 \CFA's actor system has a work stealing mechanism which uses the longest victim heuristic, introduced in Section~ref{s:victimSelect}. 753 925 In 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 926 … … 779 951 \end{figure} 780 952 781 There are two benchmarks in which \CFA's work stealing is solely evaluated. 782 The 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. 783 The following two microbenchmarks construct two such pathological cases, and compare the work stealing variations of \CFA. 784 The balance benchmarks adversari ly 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.785 The workload on the loaded cores is the same as the executor benchmark described in \ref{s:executorPerf}, but with fewer rounds. 786 The 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). 787 Given 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. 788 In the balance-multi case the ideal speedup is 0.5. 789 Note that in the balance-one benchmark the workload is fixed so decreasing runtime is expected. 953 There are two benchmarks in which \CFA's work stealing is solely evaluated. 954 The 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. 955 The following two microbenchmarks construct two such pathological cases, and compare the work stealing variations of \CFA. 956 The balance benchmarks adversarially 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. 957 The workload on the loaded cores is the same as the executor benchmark described in \ref{s:executorPerf}, but with fewer rounds. 958 The 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). 959 Given 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. 960 In the balance-multi case the ideal speedup is 0.5. 961 Note that in the balance-one benchmark the workload is fixed so decreasing runtime is expected. 790 962 In the balance-multi experiment, the workload increases with the number of cores so an increasing or constant runtime is expected. 791 963 792 On 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. 793 On the balance-multi benchmark \ref{f:BalanceMultiAMD},\ref{f:BalanceMultiIntel} the random heuristic outperforms the longest victim. 794 This 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. 964 On 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. 965 On the balance-multi benchmark \ref{f:BalanceMultiAMD},\ref{f:BalanceMultiIntel} the random heuristic outperforms the longest victim. 966 This 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. 795 967 Additionally, a performance cost can be observed when hyperthreading kicks in in Figure~\ref{f:BalanceMultiIntel}. 796 968 797 In 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. 798 On Intel \ref{f:BalanceOneIntel}, above 32 cores the performance gets worse for all variants due to hyperthreading. 969 In 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. 970 On Intel \ref{f:BalanceOneIntel}, above 32 cores the performance gets worse for all variants due to hyperthreading. 799 971 Note 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 972 801 973 \subsection{Executor}\label{s:executorPerf} 802 The microbenchmarks in this section are designed to stress the executor. 803 The 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.804 In the executor benchmark, 40'000 actors are created and assigned a group. 805 Each group of actors is a group of 100 actors who send and receive 100 messages from all other actors in their group. 806 Each time an actor completes all their sends and receives, they are done a round. 807 After all groups have completed 400 rounds the system terminates. 808 This microbenchmark is designed to flood the executor with a large number of messages flowing between actors. 974 The microbenchmarks in this section are designed to stress the executor. 975 The executor is the scheduler of an actor system and is responsible for organizing the interaction of executor threads to service the needs of a workload. 976 In the executor benchmark, 40'000 actors are created and assigned a group. 977 Each group of actors is a group of 100 actors who send and receive 100 messages from all other actors in their group. 978 Each time an actor completes all their sends and receives, they are done a round. 979 After all groups have completed 400 rounds the system terminates. 980 This microbenchmark is designed to flood the executor with a large number of messages flowing between actors. 809 981 Given 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 982 … … 822 994 \end{figure} 823 995 824 The results of the executor benchmark in Figures~\ref{f:ExecutorIntel} and \ref{f:ExecutorAMD} show \CFA with the lowest runtime relative to its peers. 825 The difference in runtime between \uC and \CFA is largely due to the usage of the copy queue described in Section~\ref{s:copyQueue}. 826 The copy queue both reduces and consolidates allocations, heavily reducing contention on the memory allocator. 827 Additionally, 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 disc iminate messages by type.828 Note that dynamic casts are usu sally not very expensive, but relative to the high performance of the rest of the implementation of the \uC actor system, the cost is significant.996 The results of the executor benchmark in Figures~\ref{f:ExecutorIntel} and \ref{f:ExecutorAMD} show \CFA with the lowest runtime relative to its peers. 997 The difference in runtime between \uC and \CFA is largely due to the usage of the copy queue described in Section~\ref{s:copyQueue}. 998 The copy queue both reduces and consolidates allocations, heavily reducing contention on the memory allocator. 999 Additionally, 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 discriminate messages by type. 1000 Note that dynamic casts are usually 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 1001 830 1002 \begin{figure} … … 841 1013 \end{figure} 842 1014 843 When 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 each other.1015 When 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 each other. 844 1016 845 1017 \begin{figure} … … 856 1028 \end{figure} 857 1029 858 The repeat microbenchmark also evaluates the executor. 859 It 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. 860 After this scatter and gather repeats 200 times the benchmark terminates. 861 The messages from the servers to the client will likely all come in on the same queue, resulting in high contention. 862 As such this benchmark will not scale with the number of processors, since more processors will result in higher contention. 863 In Figure~\ref{f:RepeatAMD} we can see that \CFA performs well compared to \uC, however by less of a margin than the executor benchmark. 864 One factor in this result is that the contention on the queues poses a significant bottleneck. 1030 The repeat microbenchmark also evaluates the executor. 1031 It 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. 1032 After this scatter and gather repeats 200 times the benchmark terminates. 1033 The messages from the servers to the client will likely all come in on the same queue, resulting in high contention. 1034 As such this benchmark will not scale with the number of processors, since more processors will result in higher contention. 1035 In Figure~\ref{f:RepeatAMD} we can see that \CFA performs well compared to \uC, however by less of a margin than the executor benchmark. 1036 One factor in this result is that the contention on the queues poses a significant bottleneck. 865 1037 As such the gains from using the copy queue are much less apparent. 866 1038 … … 879 1051 880 1052 In Figure~\ref{f:RepeatIntel} \uC and \CFA are very comparable. 881 In comparison with the other systems \uC does well on the repeat benchmark since it does not have work stealing. 882 The client of this experiment is long running and maintains a lot of state, as it needs to know the handles of all the servers. 883 When stealing the client or its respective queue (in \CFA's inverted model), moving the client incurs a high cost due to cache invalidation. 884 As such stealing the client can result in a hit in performance. 1053 In comparison with the other systems \uC does well on the repeat benchmark since it does not have work stealing. 1054 The client of this experiment is long running and maintains a lot of state, as it needs to know the handles of all the servers. 1055 When stealing the client or its respective queue (in \CFA's inverted model), moving the client incurs a high cost due to cache invalidation. 1056 As such stealing the client can result in a hit in performance. 885 1057 886 1058 This 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. 887 In 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). 1059 In 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). 888 1060 The shift for CAF is particularly large, which further supports the hypothesis that CAF's work stealing is particularly eager. 889 In both the executor and the repeat benchmark CAF performs poorly. 890 It is hypothesized that CAF has an aggressive work stealing algorithm, that eagerly attempts to steal. 891 This results in poor performance in benchmarks with small messages containing little work per message. 892 On 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. 893 This hypothesis stems from experimentation with \CFA. 894 CAF uses a randomized work stealing heuristic. 1061 In both the executor and the repeat benchmark CAF performs poorly. 1062 It is hypothesized that CAF has an aggressive work stealing algorithm, that eagerly attempts to steal. 1063 This results in poor performance in benchmarks with small messages containing little work per message. 1064 On 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. 1065 This hypothesis stems from experimentation with \CFA. 1066 CAF uses a randomized work stealing heuristic. 895 1067 In \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 1068 … … 899 1071 \setlength{\extrarowheight}{2pt} 900 1072 \setlength{\tabcolsep}{5pt} 901 1073 902 1074 \caption{Executor Program Memory High Watermark} 903 1075 \label{t:ExecutorMemory} 904 1076 \begin{tabular}{*{5}{r|}r} 905 1077 & \multicolumn{1}{c|}{\CFA} & \multicolumn{1}{c|}{CAF} & \multicolumn{1}{c|}{Akka} & \multicolumn{1}{c|}{\uC} & \multicolumn{1}{c@{}}{ProtoActor} \\ 906 \hline 1078 \hline 907 1079 AMD & \input{data/pykeExecutorMem} \\ 908 \hline 1080 \hline 909 1081 Intel & \input{data/nasusExecutorMem} 910 1082 \end{tabular} 911 1083 \end{table} 912 1084 913 Figure~\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. 915 This is a result of the copy queue data structure, as it will over allocate storage and not clean up eagerly, whereas the per envelope allocations will always allocate exactly the amount of storage needed.1085 Figure~\ref{t:ExecutorMemory} shows the high memory watermark of the actor systems when running the executor benchmark on 48 cores. 1086 \CFA has a high watermark relative to the other non-garbage collected systems \uC, and CAF. 1087 This is a result of the copy queue data structure, as it will over-allocate storage and not clean up eagerly, whereas the per envelope allocations will always allocate exactly the amount of storage needed. 916 1088 917 1089 \subsection{Matrix Multiply} 918 The matrix benchmark evaluates the actor systems in a practical application, where actors concurrently multiplies two matrices. 1090 The matrix benchmark evaluates the actor systems in a practical application, where actors concurrently multiplies two matrices. 919 1091 The 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 1092 … … 924 1096 \end{displaymath} 925 1097 926 The benchmark uses input matrices $X$ and $Y$ that are both $3072$ by $3072$ in size. 927 An 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 930 Given 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. 931 In Figure~\ref{f:MatrixAMD} \uC and \CFA have identical performance and in Figure~\ref{f:MatrixIntel} \uC pulls ahead o g \CFA after 24 cores likely due to costs associated with work stealing while hyperthreading.932 As 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. 1098 The benchmark uses input matrices $X$ and $Y$ that are both $3072$ by $3072$ in size. 1099 An 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$. 1100 1101 1102 Given 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. 1103 In Figure~\ref{f:MatrixAMD} \uC and \CFA have identical performance and in Figure~\ref{f:MatrixIntel} \uC pulls ahead of \CFA after 24 cores likely due to costs associated with work stealing while hyperthreading. 1104 As 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. 933 1105 In Figures~\ref{f:cfaMatrixAMD} and \ref{f:cfaMatrixIntel} there is little negligible performance difference across \CFA stealing heuristics. 934 1106 -
doc/theses/colby_parsons_MMAth/text/mutex_stmt.tex
rfa5e1aa5 rb7b3e41 415 415 \begin{figure} 416 416 \centering 417 \captionsetup[subfloat]{labelfont=footnotesize,textfont=footnotesize} 417 418 \subfloat[AMD]{ 418 419 \resizebox{0.5\textwidth}{!}{\input{figures/nasus_Aggregate_Lock_2.pgf}} … … 421 422 \resizebox{0.5\textwidth}{!}{\input{figures/pyke_Aggregate_Lock_2.pgf}} 422 423 } 424 \bigskip 423 425 424 426 \subfloat[AMD]{ … … 428 430 \resizebox{0.5\textwidth}{!}{\input{figures/pyke_Aggregate_Lock_4.pgf}} 429 431 } 432 \bigskip 430 433 431 434 \subfloat[AMD]{ -
doc/theses/colby_parsons_MMAth/thesis.tex
rfa5e1aa5 rb7b3e41 113 113 citecolor=blue, % color of links to bibliography 114 114 filecolor=magenta, % color of file links 115 urlcolor= cyan, % color of external links115 urlcolor=blue, % color of external links 116 116 breaklinks=true 117 117 } … … 124 124 urlcolor=black} 125 125 }{} % end of ifthenelse (no else) 126 \usepackage{breakurl} 127 \urlstyle{rm} 126 128 127 129 % \usepackage[acronym]{glossaries} -
doc/user/figures/EHMHierarchy.fig
rfa5e1aa5 rb7b3e41 29 29 1 1 1.00 60.00 90.00 30 30 4950 1950 4950 1725 31 4 1 0 50 -1 0 1 30.0000 2 135 225 1950 1650 IO\00132 4 1 0 50 -1 0 1 30.0000 2 135 915 4950 1650 Arithmetic\00133 4 1 0 50 -1 0 1 30.0000 2 150 330 1350 2100 File\00134 4 1 0 50 -1 0 1 30.0000 2 135 735 2550 2100 Network\00135 4 1 0 50 -1 0 1 30.0000 2 180 1215 3750 2100 DivideByZero\00136 4 1 0 50 -1 0 1 30.0000 2 150 810 4950 2100 Overflow\00137 4 1 0 50 -1 0 1 30.0000 2 150 915 6000 2100 Underflow\00138 4 1 0 50 -1 0 1 30.0000 2 180 855 3450 1200 Exception\00131 4 1 0 50 -1 0 12 0.0000 2 135 225 1950 1650 IO\001 32 4 1 0 50 -1 0 12 0.0000 2 135 915 4950 1650 Arithmetic\001 33 4 1 0 50 -1 0 12 0.0000 2 150 330 1350 2100 File\001 34 4 1 0 50 -1 0 12 0.0000 2 135 735 2550 2100 Network\001 35 4 1 0 50 -1 0 12 0.0000 2 180 1215 3750 2100 DivideByZero\001 36 4 1 0 50 -1 0 12 0.0000 2 150 810 4950 2100 Overflow\001 37 4 1 0 50 -1 0 12 0.0000 2 150 915 6000 2100 Underflow\001 38 4 1 0 50 -1 0 12 0.0000 2 180 855 3450 1200 Exception\001 -
doc/user/user.tex
rfa5e1aa5 rb7b3e41 11 11 %% Created On : Wed Apr 6 14:53:29 2016 12 12 %% Last Modified By : Peter A. Buhr 13 %% Last Modified On : Mon Aug 22 23:43:30 202214 %% Update Count : 55 0313 %% Last Modified On : Mon Jun 5 21:18:29 2023 14 %% Update Count : 5521 15 15 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 16 16 … … 108 108 \huge \CFA Team (past and present) \medskip \\ 109 109 \Large Andrew Beach, Richard Bilson, Michael Brooks, Peter A. Buhr, Thierry Delisle, \smallskip \\ 110 \Large Glen Ditchfield, Rodolfo G. Esteves, Aaron Moss, Colby Parsons, Rob Schluntz,\smallskip \\111 \Large Fangren Yu, Mubeen Zulfiqar110 \Large Glen Ditchfield, Rodolfo G. Esteves, Jiada Liang, Aaron Moss, Colby Parsons \smallskip \\ 111 \Large Rob Schluntz, Fangren Yu, Mubeen Zulfiqar 112 112 }% author 113 113 … … 169 169 Like \Index*[C++]{\CC{}}, there may be both old and new ways to achieve the same effect. 170 170 For example, the following programs compare the C, \CFA, and \CC I/O mechanisms, where the programs output the same result. 171 \begin{ flushleft}172 \begin{tabular}{@{}l @{\hspace{1em}}l@{\hspace{1em}}l@{}}173 \multicolumn{1}{@{}c @{\hspace{1em}}}{\textbf{C}} & \multicolumn{1}{c}{\textbf{\CFA}} & \multicolumn{1}{c@{}}{\textbf{\CC}} \\171 \begin{center} 172 \begin{tabular}{@{}lll@{}} 173 \multicolumn{1}{@{}c}{\textbf{C}} & \multicolumn{1}{c}{\textbf{\CFA}} & \multicolumn{1}{c@{}}{\textbf{\CC}} \\ 174 174 \begin{cfa}[tabsize=3] 175 175 #include <stdio.h>$\indexc{stdio.h}$ … … 199 199 \end{cfa} 200 200 \end{tabular} 201 \end{ flushleft}201 \end{center} 202 202 While \CFA I/O \see{\VRef{s:StreamIOLibrary}} looks similar to \Index*[C++]{\CC{}}, there are important differences, such as automatic spacing between variables and an implicit newline at the end of the expression list, similar to \Index*{Python}~\cite{Python}. 203 203 … … 856 856 still works. 857 857 Nevertheless, reversing the default action would have a non-trivial effect on case actions that compound, such as the above example of processing shell arguments. 858 Therefore, to preserve backwards compatibility, it is necessary to introduce a new kind of ©switch© statement, called \Indexc{choose}, with no implicit fall-through semantics and an explicit fall-through if the last statement of a case-clause ends with the new keyword \Indexc{fallthrough}/\ Indexc{fallthru}, \eg:858 Therefore, to preserve backwards compatibility, it is necessary to introduce a new kind of ©switch© statement, called \Indexc{choose}, with no implicit fall-through semantics and an explicit fall-through if the last statement of a case-clause ends with the new keyword \Indexc{fallthrough}/\-\Indexc{fallthru}, \eg: 859 859 \begin{cfa} 860 860 ®choose® ( i ) { … … 1167 1167 \end{cfa} 1168 1168 \end{itemize} 1169 \R{Warning}: specifying the down-to range maybe unex cepted because the loop control \emph{implicitly} switches the L and H values (and toggles the increment/decrement for I):1169 \R{Warning}: specifying the down-to range maybe unexpected because the loop control \emph{implicitly} switches the L and H values (and toggles the increment/decrement for I): 1170 1170 \begin{cfa} 1171 1171 for ( i; 1 ~ 10 ) ${\C[1.5in]{// up range}$ … … 1173 1173 for ( i; ®10 -~ 1® ) ${\C{// \R{WRONG down range!}}\CRT}$ 1174 1174 \end{cfa} 1175 The reason for this sema tics is that the range direction can be toggled by adding/removing the minus, ©'-'©, versus interchanging the L and H expressions, which has a greater chance of introducing errors.1175 The reason for this semantics is that the range direction can be toggled by adding/removing the minus, ©'-'©, versus interchanging the L and H expressions, which has a greater chance of introducing errors. 1176 1176 1177 1177 … … 2256 2256 Days days = Mon; // enumeration type declaration and initialization 2257 2257 \end{cfa} 2258 The set of enums are injected into the variable namespace at the definition scope. 2259 Hence, enums may be overloaded with enum/variable/function names. 2260 \begin{cfa} 2258 The set of enums is injected into the variable namespace at the definition scope. 2259 Hence, enums may be overloaded with variable, enum, and function names. 2260 \begin{cfa} 2261 int Foo; $\C{// type/variable separate namespaces}$ 2261 2262 enum Foo { Bar }; 2262 2263 enum Goo { Bar }; $\C[1.75in]{// overload Foo.Bar}$ 2263 int Foo; $\C{// type/variable separate namespace}$2264 2264 double Bar; $\C{// overload Foo.Bar, Goo.Bar}\CRT$ 2265 2265 \end{cfa} … … 2301 2301 Hence, the value of enum ©Mon© is 0, ©Tue© is 1, ...\,, ©Sun© is 6. 2302 2302 If an enum value is specified, numbering continues by one from that value for subsequent unnumbered enums. 2303 If an enum value is a nexpression, the compiler performs constant-folding to obtain a constant value.2303 If an enum value is a \emph{constant} expression, the compiler performs constant-folding to obtain a constant value. 2304 2304 2305 2305 \CFA allows other integral types with associated values. … … 2313 2313 \begin{cfa} 2314 2314 // non-integral numeric 2315 enum( ®double® ) Math { PI_2 = 1.570796, PI = 3.141597, E = 2.718282 }2315 enum( ®double® ) Math { PI_2 = 1.570796, PI = 3.141597, E = 2.718282 } 2316 2316 // pointer 2317 enum( ®char *® ) Name { Fred = "Fred", Mary = "Mary", Jane = "Jane" };2317 enum( ®char *® ) Name { Fred = "Fred", Mary = "Mary", Jane = "Jane" }; 2318 2318 int i, j, k; 2319 2319 enum( ®int *® ) ptr { I = &i, J = &j, K = &k }; 2320 enum( ®int &® ) ref { I = i, J = j,K = k };2320 enum( ®int &® ) ref { I = i, J = j, K = k }; 2321 2321 // tuple 2322 2322 enum( ®[int, int]® ) { T = [ 1, 2 ] }; … … 2361 2361 \begin{cfa} 2362 2362 enum( char * ) Name2 { ®inline Name®, Jack = "Jack", Jill = "Jill" }; 2363 enum ®/* inferred */® Name3 { ®inline Name2®, Sue = "Sue", Tom = "Tom" };2363 enum ®/* inferred */® Name3 { ®inline Name2®, Sue = "Sue", Tom = "Tom" }; 2364 2364 \end{cfa} 2365 2365 Enumeration ©Name2© inherits all the enums and their values from enumeration ©Name© by containment, and a ©Name© enumeration is a subtype of enumeration ©Name2©. … … 3818 3818 "[ output-file (default stdout) ] ]"; 3819 3819 } // choose 3820 } catch( ® Open_Failure® * ex; ex->istream == &in ) {3820 } catch( ®open_failure® * ex; ex->istream == &in ) { $\C{// input file errors}$ 3821 3821 ®exit® | "Unable to open input file" | argv[1]; 3822 } catch( ® Open_Failure® * ex; ex->ostream == &out ) {3822 } catch( ®open_failure® * ex; ex->ostream == &out ) { $\C{// output file errors}$ 3823 3823 ®close®( in ); $\C{// optional}$ 3824 3824 ®exit® | "Unable to open output file" | argv[2]; … … 4038 4038 4039 4039 \item 4040 \Indexc{sepDisable}\index{manipulator!sepDisable@©sepDisable©} and \Indexc{sepEnable}\index{manipulator!sepEnable@©sepEnable©} toggle printing the separator.4040 \Indexc{sepDisable}\index{manipulator!sepDisable@©sepDisable©} and \Indexc{sepEnable}\index{manipulator!sepEnable@©sepEnable©} globally toggle printing the separator. 4041 4041 \begin{cfa}[belowskip=0pt] 4042 4042 sout | sepDisable | 1 | 2 | 3; $\C{// turn off implicit separator}$ … … 4053 4053 4054 4054 \item 4055 \Indexc{sepOn}\index{manipulator!sepOn@©sepOn©} and \Indexc{sepOff}\index{manipulator!sepOff@©sepOff©} toggle printing the separator with respect to the next printed item, and then return to the global separator setting.4055 \Indexc{sepOn}\index{manipulator!sepOn@©sepOn©} and \Indexc{sepOff}\index{manipulator!sepOff@©sepOff©} locally toggle printing the separator with respect to the next printed item, and then return to the global separator setting. 4056 4056 \begin{cfa}[belowskip=0pt] 4057 4057 sout | 1 | sepOff | 2 | 3; $\C{// turn off implicit separator for the next item}$ … … 4129 4129 6 4130 4130 \end{cfa} 4131 Note, a terminating ©nl© is merged (overrides) with the implicit newline at the end of the ©sout© expression, otherwise it is impossible to toprint a single newline4131 Note, a terminating ©nl© is merged (overrides) with the implicit newline at the end of the ©sout© expression, otherwise it is impossible to print a single newline 4132 4132 \item 4133 4133 \Indexc{nlOn}\index{manipulator!nlOn@©nlOn©} implicitly prints a newline at the end of each output expression.
Note:
See TracChangeset
for help on using the changeset viewer.