원시데이터 수집 시스템
선정목록으로

Reciprocating Locks

관련 필름·전자재료 · (16) CPI(투명 폴리이미드)

기본 정보

저자
  1. Dave Dice — Oracle Labs, USA
  2. Alex Kogan — Oracle Labs, USA
DOI
10.1145/3710848.3710862
저널
–
발행년도
2025
발행기관
–
피인용수
1
라이선스
cc-by-nd
논문 유형
–
언어
–
원문 페이지
https://doi.org/10.1145/3710848.3710862
토픽
High voltage insulation and dielectric phenomena
OpenAlex ID
W4408029643

평가 내용

관련도
관련
사업분야
필름·전자재료 · (16) CPI(투명 폴리이미드)
부 분야
–
R&D 측면
–
확신도
–
근거 용어
–
판단 근거
임베딩 유사도 기반 평가로 '필름·전자재료 > CPI(투명 폴리이미드)' 분야에 선정된 논문입니다.
R&D 활용 포인트
–
평가 입력
–

초록

We present Reciprocating Locks, a novel mutual exclusion locking algorithm, targeting cache-coherent shared memory (CC), that enjoys a number of desirable properties. The doorway arrival phase and the Release operation both run in constant-time. Waiting threads use local spinning and only a single waiting element is required per thread, regardless of the number of locks a thread might hold at a given time. While our lock does not provide strict FIFO admission, it bounds bypass and has strong anti-starvation properties. The lock is compact, space efficient, and has been intentionally designed to be readily usable in real-world general purpose computing environments such as pthreads, or C++. We show the lock exhibits high throughput under contention and low latency in the uncontended case. Under sustained contention, Reciprocating Locks generate less coherence traffic than MCS and CLH. The performance of Reciprocating Locks is competitive with and often better than the best state-of-the-art scalable queue-based spin locks.

본문 55,634자

본문 펼치기
We present Reciprocating Locks, a novel mutual exclusion locking algorithm, targeting cache-coherent shared memory (CC), that enjoys a number of desirable properties.The doorway arrival phase and the Release operation both run in constant-time.Waiting threads use local spinning and only a single waiting element is required per thread, regardless of the number of locks a thread might hold at a given time.While our lock does not provide strict FIFO admission, it bounds bypass and has strong anti-starvation properties.The lock is compact, space efficient, an d ha s be en intentionally designed to be readily usable in real-world general purpose computing environments such as pthreads, or C++.We show the lock exhibits high throughput under contention and low latency in the uncontended case.Under sustained contention, Reciprocating Locks generate less coherence traffic than MCS and CLH.The performance of Reciprocating Locks is competitive with and often better than the best state-of-the-art scalable queue-based spin locks. Introduction Locks often have a crucial impact on the performance of parallel software, hence they remain the focus of intensive research with a steady stream of algorithms proposed over the last several decades. The Reciprocating Lock Algorithm Briefly, under contention, Reciprocating Locks1 partitions the set of waiting threads into two disjoints lists, which we call the arrival and entry segments.Threads arriving to acquire the lock will push (prepend) themselves onto a stack, using an atomic exchange operation, forming the arrival segment.When the owner releases the lock, it first tries to pass ownership to any threads found in the entry segment.Otherwise, if the entry segment is found empty, the thread then uses an atomic exchange to detach the entire current arrival segment (setting it empty), which then becomes the next entry segment, and then passes ownership to the first element of the entry segment. The Reciprocating Lock Algorithm In Reciprocating Locks, a lock instance consists of an arrival word.We deem the lock held if the arrival word is non-zero.Specifically, a value of 0 (nullptr) encodes the unlocked state, 1 (LOCKEDEMPTY) encodes the state of simple locked -locked with an empty arrival segment -and other values encode being locked, where the remainder of the arrival word points to a stack of threads that have recently arrived at the lock and are waiting for admission, forming the arrival segment. The Reciprocating Lock Algorithm Threads arriving to acquire the lock use an atomic swap (exchange) operator to install the address of a thread-private waiting element into the arrival word.If the return value from the atomic exchange was nullptr then the arriving thread managed to acquire the lock without contention and can immediately enter the critical section.Otherwise, our thread has encountered contention and must wait.By virtue of the atomic exchange, the thread has managed to push its waiting element onto the arrival segment.The non-nullptr value returned from the atomic exchange identifies the next thread in the stack.Similar to the HemLock [20] and CLH [12,34] lock algorithms, a thread knows only the identity of its immediate neighbor in the arrival segment, and unlike MCS, no explicit linked list of waiting threads is formed or required 2 .That is, the arrival stack is implicit with no next pointer fields in the waiting elements.Our thread then proceeds to local spinning on a flag field within its waiting element.This flag will eventually be set during normal ownership succession by some thread running in the Release operation, passing ownership to our waiting thread.Our thread, still executing in Acquire and now the owner, arranges to convey the address of the next thread in the entry segment, which was obtained from the atomic exchange, to the subsequent corresponding Release operation.The thread identified by that address will subsequently serve as the successor to our current thread.Our thread finally enters the critical section. The Reciprocating Lock Algorithm In the corresponding Release operator, if a successor was passed from the corresponding Acquire operator, we simply enable that thread to enter the critical section by setting the flag in its waiting element.Otherwise, we attempt to use an atomic compare_and_exchange (CAS) operation to swing the arrival word from simple locked state back to unlocked.If the CAS was successful then no waiting threads exist and the lock reverts to unlocked state.If the CAS failed, however, additional newly arrived threads must be present on the arrival segment.In that case we employ an atomic exchange to detach the entire arrival segment, leaving the arrival word in simple locked state, encoded as 1.We then pass lock ownership to the first thread in the detached segment by setting the flag in its waiting element. The Reciprocating Lock Algorithm Crucially, under contention, threads arrive and join the arrival segment.While the entry segment remains populated, ownership is passed through the entry segment elements in turn.When the current entry segment becomes empty, the Release operator detaches the arrival segment, (via an atomic exchange) which then becomes the next entry segment.Threads migrate, in groups, from the arrival segment to the entry segment.The arrival segment consists of those newly arrived threads currently pushed onto the stack anchored at the arrival word while entry segment reflects a set of threads that have already been detached from the arrival stack. The Reciprocating Lock Algorithm The Release operator consults the entry segment firstvia the successor reference passed from Acquire to Release -and passes ownership to the successor if possible.The sequence of successor references passed from Acquire to Release constitutes the entry segment.But if the entry segment is empty -the passed successor argument is nullptr -Release then attempts to replenish the entry segment by detaching the arrival segment, and transferring ownership to the first element.In the event the arrival segment is found empty, the lock reverts to unlocked state. 2 Regarding terminology, say thread arrives and pushes itself onto the stack and then follows.In terms of arrival, is 's predecessor.But in terms of subsequent admission order, in Reciprocating Locks, is 's successor. There is no such situational distinction between arrival and admission for FIFO The arrival segment is implemented by means of a concurrent pop-stack [8], where the key primitives are push and detach-all, which makes our technique immune to the A-B-A pathology [42].By convention, in Reciprocating Locks, only the current lock holder detaches the arrival segment. There is no such situational distinction between arrival and admission for FIFO The waiting element is similar to the CLH or MCS "queue node".In our implementation, we opt to place a thread's wait element in thread-local storage (TLS).As a thread can wait on at most one lock at any given time, such a singleton suffices, and tightly bounds memory usage. There is no such situational distinction between arrival and admission for FIFO Given that we form a stack for arriving threads, admission order is LIFO within a segment, but remains FIFO between segments.As such, if thread 1 pushes itself onto the arrival segment in Acquire, and then waits, and 2 arrives and pushes itself after 1, then a given thread 2 can bypass or overtake 1 at most once before 1 is next granted ownership, providing thread-specific bounded bypass and thus avoiding indefinite starvation.Alternatively, we could say Reciprocating Locks provides classic -bounded bypass (worst case) where reflects the cardinality of the population of threads that might compete for the lock, yielding population bounded bypass. Implementation Details In Listing-1 we show an implementation of Reciprocating Locks in modern C++.For brevity, this version expresses the critical section as a C++ lambda expression and passes the variables succ and eos from the acquire phase to the corresponding release phase.If desired, it is possible to collapse those into just one variable by a change in encoding.Under a legacy locking interface, with distinct lock() and unlock() operators, context may be passed via extra fields in the lock body or conveyed via thread-local storage.Nonescaping lambdas are efficient and add no particular runtime overhead 3 .The assert statements in the listing express invariants and do not constitute checks against errant usage of the lock. Implementation Details We also assume the existence of a "polite" Pause() operator for busy-waiting.For encoding the arrival word, we assume that low-order bit of wait element addresses are 0. We further assume the existence of a wait-free atomic exchange operator.To maintain progress properties, the implementation thereof should not be via loops that employ optimistic compare-and-swap or load-locked and store-conditional primitives.In particular we assume that C++ std::atomic exchange and compare_and_exchange primitives are implemented in a wait-free fashion, as is the case on AMD or Intel x86 processors or ARM processors that support the LSE instruction subset.▶ Simple uncontended Acquire and Release : 1 Thread 1 arrives at Line-14 to acquire lock .'s arrival word is currently nullptr, indicating that is in unlocked state. 2 At Line-17, 1 initializes its thread-specific waiting element, , in anticipation of potential contention. 3 1 then swaps the address of into 1's arrival word in Line-20.The atomic exchange returns nullptr, indicating uncontended acquisition, so control passes into the critical section at Line-47.When the critical section completes execution, control enters the release phase at Line-50. 4 As there are no successors, execution reaches the CAS operation at Line-66.As no additional threads have arrived, the CAS is successful and control returns from Line-66, completing the operation.The CAS reverts the arrival to unlocked state. Implementation Details ▶ Onset of contention In this scenario we show how to recover from a race in Acquire where a thread pushes its wait element onto the stack but, because of other arriving threads, is not able, in the Release operation, to CAS the arrival word back to 1, and its element becomes "submerged" on the arrival stack.We tolerate this situation by conveying the address of that submerged element through the segment, during succession, allowing us to treat the buried element as the effective end-of-segment (equivalent to nullptr) and otherwise ignore it.We convey that address through the wait element Gate field, when passing ownership.In this case we say we have a zombie terminal element.During succession a thread checks the address of its successor to determine if matches the submerged terminal element. 1 Lock is in unlocked state and thread 1 arrives and acquires the lock. 1 executes the atomic exchange at Line-20 to install the address of its wait element , which we will designate 1, into 's arrival word, the exchange returns 0 (nullptr), so 1 now holds the lock. 1 enters the critical section. 2 Thread 2 now arrives to acquire and exchanges the address of its wait element, 2 into the lock's arrival word. 2's successor is 1 and 2 enters the waiting loop at Line-30. 3 Thread 3 also arrives and pushes the address of its wait element, 3, onto the arrival stack. 3, whose successor is 2, enters the waiting loop at Line-30. 4 1 finishes execution of the critical section and then starts the Release operation.At Line-66, 1 attempts uses a CAS to try to release replacing the address of its 1 with nullptr encoding.The CAS fails, however, as other threads have arrived, and the arrival word now points to 3 instead of 1.At this point, 1's wait element 1 is "buried" or "submerged" in the arrival stack, residing at the distal end. 5 As the CAS failed, control reaches Line-73 where 1 detaches the new arrivals.The atomic exchange replaces 3 with a special LOCKEDEMPTY distinguished value, which indicates the lock is held but that the arrival list is empty and has been previously detached. 6At Line-76, 1 stores its eos (end-of-segment) address, which refers to 1, into 3's Gate field.This both enables 3 and conveys the address of 1 to 3. 1 has completed is locking episode. 7 3, at Line-30, observes that its Gate field is now 1.Its local eos variable now refers to 1. 3 now has ownership.The comparison at Line-37 does not match, so 3 enters the critical section. 8 3 executes the critcal section.Upon return from the critical section, 3 at Line-53, recognizes that it has a successor, 2 (2), on the detached entry segment.At Line-58, 3 stores its eos value, 1, into 2's Gate field.The store conveys both the identity of the end-of-segment and ownership. 3 has finished its locking episode and returns at line-59. 9 2 observes at Line-30 that is has received ownership, and its eos value is now 1. 2's indicated successor is 1 (1) and the comparsion at Line-37 matches, so we have reached the end of the detached entry segment. 2 then clears its local succ successor pointer and sets its local eos value to LOCKEDEMPTY. 10 2 enters and executes the critical section. 11Control in 2 reaches line-66, where the CAS succeeds and swings the arrival word from LOCKEDEMPTY to unlocked. Implementation Details We note that a contended Release operation might need to execute two atomic operations, the CAS at Line-66 and the exchange at Line-76, potentially increasing RMR complexity [4,7].In practice, given the narrow window, the underlying cache line tends remain to local modified state.If desired, to mitigate this concern, we could condition the CAS on an immediate prior load, reducing the number of futile CAS operations.We found this optimization provided no observable benefit, and did not use it. Implementation Details In the case where is submerged, we use 's address for addressed-based comparisons (Line-37) as a distinguished marker or sentinel to indicate the logical end-of-segment. itself, however, will not be subsequently accessed by succession within the segment.Elements associated with a given thread can appear on at most one segment at any time, but, when an address is used as an end-of-segment marker, it is possible that it appears on both the arrival segment and entry segment. Implementation Details We observe that the eos value could also reside in a field the lock body, potentially sequestered and isolated on a dedicated cache line, instead of in the waiting elements.While viable, that approach increases the size of the lock body, and increases induced coherence traffic.Instead, we borrow a technique from Compact NUMA-Aware Locks (CNA) [17] and avoid such shared central fields by propagating information -in this case the address of the terminal element of the segment -through the chain of waiting elements. Implementation Details Terminus, end-of-segment, eos, marker, sentinel, ghost, zombie, alternative end, Vesper, punctuation, virtual, phantom end mark, tombstone, section mark; pilcrow, fleuron, hedera, dinkus, -30-Eos; end-of-segment; terminus; Vesper; Astraeus; fini; Boustrophedonic ▶ Sustained contention 1 Lock is initially in unlocked state.Thread 1 arrives to acquire . 1's exchange operation at Line-20 installs the address of 1's wait element, 1, into 's arrival word.As the exchange returned nullptr, 1 has acquired the lock. 2 1 enters and executes the critical section. 3While 1 holds , thread 2 arrives and 2 pushes onto the arrival stack.The exchange operation at Line-20 returns 1 into 2's local tail variable.As tail is non-0, 2 must wait at Line-29. 2 local succ variable refers to 1. 4 With 1 still holding , 3 also arrives and uses the atomic exchange to push its element 3 onto the arrival stack.The exchange returns 2 and 3's succ variable points to 2.The arrival stack consists of 3 followed by 2 followed by 1, although 1 is "buried" and will be excised during subsequent succession.The entry segment is empty. 3 waits on 3 at Line-30 5 Similarly, 4 arrives and pushes 4 onto the arrival stack and then waits. 4's successor variable points to 3. 6 1 eventually completes the critical section and then executes the Release phase at Line-50.As 1's succ variable is nullptr, indicating an empty entry segment, 1 then attempts the CAS, at Line-66 which fails. 1 then executes exchange(LOCKEDEMPTY) to detach the arrival segment at Line-73.The exchange operator returns 4.The arrival segment is now empty and the entry segment consists of 4 then 3 then 2 then 1. 1 passes ownership to 4 at Line-76, passing the address of 1 as the end-of-segment marker. 7 4 is now the owner and departs its waiting phase at Line-31, having received 1 as the end-of-segment address.The end-of-segment address check at Line-37 does not match, so 4 enters the critical section. 8while 4 holds , 5 and then 6 arrive to acquire , pushing 5 and then 6, respectively, onto the arrival stack.The arrival segment consists of 6 then 5 and the detached entry segment is just 3 and 2 and 1.When 5 arrived, its exchange replaced LOCKEDEMPTY with 5.Crucially, Line-25 converted LOCKEDEMPTY, which is encoded as 1, to a effective successor value of nullptr. 9 4 releases the lock.As 3 is 4's the successor, we grant ownership to 3 at Line-58, again passing 1 as the end-of-segment address. 10 3 departs its wait phase at Line-31 and enters and executes the critical section. 11 3 releases the lock, observing 2 as its successor and grants ownership to 2 at Line-58, again, passing 1 as the end-of-segment, 12 2 departs its wait phase at line-31.In this particular step, the address check at Line-37 matches, and 2 annuls its succ variable and sets its eos to LOCKEMPTY.We have reached the end of the entry segment, which is now exhausted. 2 enters and executes the critical section. 13 2 executes the release phase, and since succ is nullptr at Line-53, the current entry segment is empty. 2 then attempts the CAS at line 66, which tries to replace LOCKEDEMPTY with unlocked.The CAS fails as the arrival segment is populated with 6 and 5 and the arrival word points to 6. 2 then detaches the new arrivals at Line-73 and passes ownership to 6 (via 6) at Line-76, and also conveying the end-of-segment address, which is now LOCKEDEMPTY, to 6. 14 6 exits the waiting loop at Line-30, noting that eos is now LOCKEDEMPTY. 6's successor is 5. 6 enters the critical section. 15 6 completes the critical section and executes the release phase.As 6's succ variable refers to 5, we pass ownership and the end-of-segment address (LOCKEDEMPTY at this juncture) to 5. 16 5 recognizes ownership at Line-30 and then enters the critical section at Line-47. 17 5 releases the lock.It's succ value is nullptr to it the attempts the CAS at Line-66.In this case the CAS succeeds, replacing LOCKEDEMPTY with the unlocked encoding of nullptr. is restored to unlocked state. Additional Requirements practical; pragmatic; de facto; QoI = quality of implementation, desiderata Additional Requirements We target lock algorithms that are suitable for environments such as the Linux kernel, as a replacement for the user-level pthreads_mutex primitive, or for use in runtime environments such as the HotSpot Java Virtual Machine (JVM), which is written in C++.As such, we identify additional de-facto requirements for general purpose lock algorithms.Safe Against Prompt Lock Destruction Various lock algorithms perform stores in the Release operation that potentially release ownership, but then perform additional accesses to fields in the lock body to ensure succession and progress.This can result in a class of unsafe use-after-free memory reference errors [9,37].A detailed description of such an error can be found in [20].All algorithms for use in the linux kernel or in the pthreads environment are expected to be prompt lock destruction safe.Support for Large Numbers of Extant Threads The algorithms must support the simultaneous participation of an arbitrary number of threads, where threads are created and destroyed dynamically, and the peak number of extant threads is not known in advance.Support for Large Numbers of Extant Locks Similarly, the algorithm needs to support large numbers of lock instances, which can be created and destroyed dynamically.Recent work [32] shows the Linux kernel has more than 6000 statically initialized lock instances.Again, the number of locks is not know in advance, as drivers load, and unload, for instance, or as data structures containing locks dynamically resize.Plural Locking A given thread is expected to be able to lock and hold a large number of locks simultaneously.In the Linux kernel, for instance, situations arise when 40 or more distinct locks are held by a single thread at a given time, as evidenced by the MAX_LOCK_DEPTH tunable, which is used by the kernel's "lockdep" facility to track the set of locks held in an explicit per-thread list for the purposes of detecting potential deadlock.Furthermore, locks must be able to be released in non-LIFO imbalanced order as it is fairly common to acquire a lock in one routine, return, and then release the lock in the caller. Space Efficient We expect the lock algorithm to be frugal and parsimonious with regard to space usage.Critically, any algorithms that require per-lock and per-thread storage -with ℎ * space consumption -such as Anderson's Array-Based Queue Lock [6], are not suitable.FIFO as a non-goal We also note that many real-world lock implementations, such as the current implementation of Java's "synchronized" in the HotSpot Java Virtual Machine, the java.util.Concurrent.ReentrantLock, and the default pthread_mutex on Linux, are non-FIFO, and in fact permit unbounded bypass and indefinite starvation.Relatedly, Compact NUMA-Aware Locks (CNA) [17] intentionally imposes non-FIFO admission order to improve throughput on NUMA platforms, trading aggregate throughput against strict FIFO ordering.In fact, strict FIFO locking is an antipattern for common practical lock designs, as it suffers from reduced throughput compared to more relaxed admission schedules, and has shortcomings when used with waiting techniques that deschedule threads, or when involuntary preemption is in play [16,19].Forgoing strict FIFO admission schedules allows more opportunism that in some circumstances may translate into improved throughput. Space Efficient Given these particular constraints, we exclude a number of algorithms from consideration.Dvir's algorithms [23], Rhee's algorithm [40], Lee's HL1 and HL2 [30,31], and Jayanati's "Ideal Queued Spinlock" [28] [29] algorithms, when simplified for use in cache-coherent (CC) environments, all have extremely simple and elegant paths and low RMR complexity, suggesting they would be competitive and good candidates, but they do not readily tolerate multiple locks being held simultaneously.The above tend to use so-called "nodetoggling" and "node-switching" techniques -also called "two-face" by Lee -that, while they work well when a thread holds at most one lock, are awkward for general purpose use.Our specific concerns are space blow-up due to the need to maintain toggle element pairs and a "face" index for pairs of locks and threads, in addition to the requirement that we re-associate that metadata with the lock instance at releasetime.Some of Dvir and Lee's algorithms are also not safe against prompt lock destruction. Related Work While mutual exclusion remains an active research topic [1-3, 12, 15-18, 22-24, 26-29, 36, 39, 41] we focus on locks closely related to our design. Related Work Simple test-and-set or polite test-and-test-and-set [41] locks are compact and exhibit excellent latency for uncontended operations, but fail to scale and may allow unfairness and even indefinite starvation.Ticket Locks are compact and FIFO, and also have excellent latency for uncontended operations, but they also fail to scale because of global spinning, although some variations attempt to overcome this obstacle, at the cost of increased space [18,38].For instance, Anderson's array-based queueing lock [5,6] is based on Ticket Locks but provides local spinning.It employs a waiting array for each lock instance, sized to ensure there is at least one array element for each potentially waiting thread, yielding a potentially large footprint.The maximum number of participating threads must be known in advance when initializing the lock.TWA [18] is a variation on ticket locks that reduces the incidence of global spinning. Related Work Queue-based locks such as MCS or CLH are FIFO and provide local spinning and are thus more scalable.MCS is used in the linux kernel for the low-level "qspinlock" construct [10,11,33].Modern extensions of MCS edit the queue order to make the lock NUMA-Aware [17].MCS readily allows editing and re-ordering of the queue of waiting threads, [15,17,35] whereas editing the chain is more difficult under CLH, HemLock and Reciprocating Locks, where there are no explicit linked lists. Related Work CLH is extremely simple, has excellent RMR complexity, and requires just an single atomic exchange operation in the Acquire operation and no atomic read-modify-write instructions in Release.Unfortunately the waiting elements migrate between threads, which may be inimical to performance in NUMA environments.CLH locks also require explicit constructors and destructors, which may be inconvenient 4 .Our specific implementation uses a variation on Scott's [41] Figure 4.14, which converts the CLH lock to be context-free [44], adhering to a simple programming interface that passes just the address of the lock, albeit at the cost of adding an extra field to the lock body to convey the address of the head waiting element to Release. Related Work HemLock combines aspects of both CLH and MCS to form a lock that has very simple waiting node lifecycle constraints, is context-free but still scales well in common usage scenarios.HemLock does not provide constant remote memory reference (RMR) complexity [23] in scenarios where a thread holds multiple contended locks.In this situation the single node suffers from multi-waiting [20].Similar to MCS, Hem-Lock lacks a constant-time unlock operation, whereas the unlock operator for CLH and Tickets is constant-time.Unlike MCS, HemLock requires active synchronous back-and-forth communication in the unlock path between the outgoing thread and its successor to protect the lifecycle of the waiting 4 Many lock implementations require just trivial constructors to set the lock fields to 0 or some constant, and trivial destructors, which do nothing.The Linux kernel spinlock_t/qspinlock_t interface provides a constructor, but does not even expose a destructor.Similarly, C++ std::mutex is allowed to be trivially destructible, meaning storage occupied by trivially destructible objects may be reused without calling the destructor.Under both GCC g++ version 13 and Clang++ Version 18, is_trivially_destructible reports True for std::mutex, and as such, destructors do not run.This situation could be rectified by recompiling, but we would also need to recompile all libraries transitively depended on by the application, including those deployed in shared libraries in binary-only form on the system.element.We note, however, that HemLock remains constanttime in the Release operator to the point where ownership is conveyed to the successor.HemLock uses address-based transfer of ownership, writing the address of the lock instead of a boolean, differentiating it from MCS and CLH.Reciprocating Locks, like HemLock, requires just a singleton per-thread waiting element allocated in thread-local storage. Related Work We opted to exclude NUMA-aware locks such as Cohort Locks [21,22] and Compact NUMA-Aware Locks (CNA) [17] from consideration.We excluded Fissile Locks and GCR [16] as they have lax time-based anti-starvation mechanism.Fissile, specifically, depends on the owner of the inner lock to make progress to monitor for starvation. Related Work In Table-1 we compare the attributes of various local algorithms.Red -colored cells indicate potential undesirable properties.Note that all the locks provide a constant-time doorway phase.In the following we explain the meaning of each property. Related Work Spinning: reflects whether the lock utilizes local, global or semi-local [20] spinning.Constant-time Unlock: indicates if the lock Release operation is bounded.As noted above, HemLock is constant-time up to the point where the lock is either released or transferred to a successor, but the Release operator, for reasons of memory safety, then waits for the successor to acknowledge transfer of ownership before the memory underlying the queue element can be potentially reused.Specifically, in HemLock an uncontended Release operation is constant-time and a contended Release is constant-time up to and including the point where ownership is conveyed to the successor.FIFO: indicates the lock provides strict FIFO admission.Context-free: indicates additional information does not need to be transferred from the lock operator to the corresponding Release operation.Path Complexity -Acquire and Path Complexity -Release : we measured the size of the Acquire and Release methods in units of platform independent LLVM intermediate representation (IR) instructions, as emitted by clang++-18, which serves as a simple measure for path complexity.We note that much of the complexity found in TWA manifests through the use of the hash function which maps lock address and ticket value pairs to slots in the waiting array.On-Stack: indicates the queue elements, if any, may be allocated on-stack.This also implies the nodes do not migrate and have a tenure constrained to the duration of the locking episode.Nodes Circulate: queue elements migrate between threads.This often implies the need for an explicit queue element lifecycle management system and precludes convenient on-stack allocation of queue elements.Migration may also be unfriendly to performance in NUMA environments.Explicit CTOR/DTOR Required: indicates the lock requires non-trivial constructors or destructors.CLH, for instance, requires destructors to run to release the wait elements referenced in the lock, to avoid memory leaks.Maximum Remote Misses per We used the ARM l2d_cache_inval hardware performance counter, which tallies L2 cache invalidation events, as simple proxy for coherence traffic -both latency and bandwith.We report the number of l2d_cache_inval events per episode. Related Work As can be seen, Reciprocating Locks is parsimonious and incurs just 4 invalidations per episode, while CLH requires 5 5 .Ticket locks require (10 in our example) invalidations per episode, where is the number of participating threads, given the global spinning.The number of misses incurred by CLH, MCS, HemLock and Reciprocating Locks is constant and not a function of the number of threads.These empirically-derived results align closely with a static analysis of the code and the expected number of coherence misses in the Acquire and Release paths.Space Complexity: reflects the space complexity of the lock algorithm where is the number of active threads, is the number of extant locks, is the number of locks currently held plus the number of threads currently waiting on locks, is the size of the waiting element. is the size of a lock instance.When a lock algorithm requires context to be passed from Acquire to the corresponding Release, we set to 2 to indicate that our implementation allocated an extra word in the lock body to pass such information.Implementations that require context can avoid that space requirement in the lock body if they opt to pass context information by other means, such as via thread-local storage, in which case would be 1.HemLock is context-free, so the per-lock space usage is just 1, while Ticket Locks and TWA require 2 words per lock.TWA requires an additional 4096 words for the global waiting table that is shared over all thread and lock instances. 5We observed similar ratios with performance counters that reported the number of "snoop" messages, and on Intel by counting OFFCORE requests.We also observed in passing, while examining data from hardware performance counters, that CLH and MCS suffered from more stalls (both event counts and duration) from misses than did Reciprocating locks.CLH in particular executes a dependent load in the critical path in the arrival doorway on the address returned from the atomic exchange.The address to be loaded from is not known until after the exchange returns, denying the processor the ability to speculate or execute out-of-order. Empirical Performance Results Unless otherwise noted, all data was collected on an Oracle X5-2 system system having 2 sockets, each populated with an Intel Xeon E5-2699 v3 CPU running at 2.30GHz.Each socket has 18 cores, and each core is 2-way hyperthreaded, yielding 72 logical CPUs in total.The system was running Ubuntu 20.04 with a stock Linux version 5.4 kernel, and all software was compiled using the provided GCC version 9.3 toolchain at optimization level "-O3".64-bit C or C++ code was used for all experiments.Factory-provided system defaults were used in all cases, and Turbo mode [43] was left enabled.In all cases default free-range unbound threads were used, with no pinning of threads to processors.At above 18 ready threads, the kernel starts to place additional threads onto the second socket, and NUMA effects come into play.We implemented all user-mode locks within LD_PRELOAD interposition libraries that expose the standard POSIX pthread_ mutex_t programming interface using the framework from [22].This allows us to change lock implementations by varying the LD_PRELOAD environment variable and without modifying the application code that uses locks.The C++ std::mutex construct is implemented directly via pthread_ mutex primitives, so interposition works for both C and C++ code.All lock busy-wait loops on Intel used the PAUSE instruction and YIELD on ARMv8.To reduce false sharing, all waiting elements were aligned and sequestered at 128-byte boundaries, and, for the "MutexBench" benchmarks, below, the lock instances where similarly sequestered.For the CLH, MCS, and Reciprocating Locks implementations used in the benchmark section of this paper, we elected to pass any additional context information via extra fields in the lock instance. MutexBench benchmark The MutexBench benchmark spawns concurrent threads.Each thread loops as follows: acquire a central lock L; execute a critical section; release L; execute a non-critical section.At the end of a 10 second measurement interval the benchmark reports the total number of aggregate iterations completed by all the threads.We report the median of 7 independent runs in Figure -1a where the critical section advances a shared global std::mt19937 Mersenne Twister pseudo-random number generator (PRNG) one step, and the non-critical section is empty, subjecting the lock to extreme contention.(At just one thread, this configuration also constitutes a useful benchmark for uncontended latency).The -axis reflects the number of concurrently executing threads contending for the lock, and the -axis reports aggregate throughput.For clarity and to convey the maximum amount of information to allow a comparison of the algorithms, the -axis is offset to the minimum score and the -axis is logarithmic. MutexBench benchmark We ran the benchmark under the following lock algorithms: MCS is classic MCS.To avoid memory allocation during the measurement interval, the MCS implementation uses a thread-local stack of free queue elements.CLH is CLH based on Scott's CLH variant with a standard interface Figure-4.14 of [41]; For the MCS and CLH locks, our implementation stores the current head of the queue -the owner -in a field adjacent to the tail, so the lock body size was 2 words.CLH presents something of a challenge when used under the pthread_mutex interface.First, pthreads allows the programmer to use trivial initializers -setting the mutex body to all 0 -and avoid calling pthread_mutex_init.To compensate, we modified pthread_mutex_lock to populate such an uninitialized lock with the CLH "dummy node" lazily, ondemand, on the first lock operation.In pthread_mutex_destroy we free the node, if populated, but many applications also do not call pthread_mutex_destroy, which constitutes a memory leak.As such, to allow CLH to be included, we avoided applications that create and then abandon large numbers of locks in a dynamic fashion.Ticket is a classic Ticket Lock; HemLock is the HemLock algorithm, with the CTR (coherence traffic reduction) optimization. MutexBench benchmark In Figure-1a we make the following observations regarding operation at maximal contention with an empty critical section: MutexBench benchmark • At 1 thread the benchmark measures the latency of uncontended Acquire and Release operations.Ticket Locks are the fastest, followed closely by HemLock, Reciprocating Locks, CLH and MCS.• As we increase the number of threads, Ticket Locks initially do well but then fade, exhibiting a precipitous drop in performance.TWA is the clear leader in the "middle" area of the graph, between 4 and 16 threads.• Broadly, at higher thread counts, HemLock performs slightly better than or the same as CLH or MCS, while Reciprocating Locks provides the best throughput. MutexBench benchmark In Figure-1b we pass arguments to MutexBench that configure it to implement a delay in the non-critical section.Each thread has a private std::mt19937 pseudo-random number generator.The non-critical section generates, using the private PRNG, a uniform random number in the range [0−250) and then advances its private PRNG that many steps.(We take care to make sure this operation can not be optimized away by consuming the PRNG value at the end of the thread's run).As above, the critical section advances the shared PRNG one step.As can be seen, we enjoy positive scalability up to about 5 threads.At higher thread counts, Reciprocating Locks manages to exhibit the least reduction in scalability. MutexBench benchmark In Figure -1c and Figure -1d, we show the results of Mu-texBench on an ARMv8 (aarch64) system, showing that the relative performance of the various algorithms remains portable over disparate architectures.The ARMv8 system was an Ampere Altra Max NeoVerse-N1 with 128 processors on a single socket and was running Ubuntu 24.04.We compiled all code using the -mno-outline-atomics -march= armv8.2-a+lseflags in order to allow direct use of modern atomic exchange, CAS and fetch-and-add instructions instead of the legacy LL-SC (load-locked store-conditional) forms thereof. std::atomic In Figure -2a, our C++ atomic exchange benchmark defines a simple structure type S that contains 5 32-bit integers.Each thread declares a local S instance, and we also declare a shared global std::atomic<S> A {}.The C++ compiler and runtime implement std::atomic for such objects by hashing the address of the instance into an array of mutexes, and acquiring those as needed to implement the desired atomic action.Each thread loops for 10 seconds, using std::atomic<S>::exchange to swap its local copy with the shared global, and we then report aggregate throughput rate, in terms of completed exchange operations, at the end of the measurement interval.The figure depicts the median score of 7 runs and the overall ranking of the locks is similar to that observed under MutexBench.Figure-2b is similar, but instead of std::atomic:exchange, we use std::atomic:load to fetch the shared global, make a local copy, increment the 1st of the five constituent integer fields in that copy, and then call std::atomic:compare_ exchange_strong (CAS) in an inner loop to try replace the global copy with the updated local version.The load operator acquires and releases all necessary covering locks, as does the compare_exchange_strong operator.If the CAS fails, we update our fresh local copy (returned from CAS) and retry.At the end of the 10 second measurement interval we report total number of successful CAS operations.The graph reports the median score of 7 runs.For both benchmarks, the relative ranks of the various lock algorithms remains similar to what was observed with MutexBench. LevelDB In Figure-3 we used the "readrandom" benchmark in Lev-elDB version 1.20 database6 varying the number of threads and reporting throughput from the median of 5 runs of 50 Discussion ▶Constant-time arrival doorway and Release paths, as a consequence of having desirable progress properties, may yield more predictable performance.Furthermore, such designs are more inherently amenable to "polite" waiting, where a thread voluntarily deschedules itself and explicitly waits to be notified of transfer of ownership, by means of thread identity-based waiting primitives, such as park-unpark [14] or address-based waiting, such as the linux futex [25] primitive, which underlies the pthreads synchronization services.Use of such primitives allows the implementation to avoid toxic waiting policies, such as unbounded busy-waiting; periodic polling via timed sleep operations; or operating-system advisory yield calls.Specifically, having constant-time paths means contending threads wait on only one conditiontransfer of ownership -and have one waiting phase.In contrast, locks such as MCS or HemLock may need to wait on additional conditions.▶Lifecycle management : In classic MCS the address of the owner's "queue node" must be passed from an acquire operation to the corresponding release.Relatedly, that queue node must remain extant during the entire acquire-release period, and can not be use for other locking operations.In Reciprocating Locks, the element needs to remain extant only for the duration of the acquire operation, affording the implementer more latitude as to how and where the element is allocated.A singleton element allocated in thread-local storage suffices.▶Passing of context from acquire to release : Like MCS and CLH, Reciprocating Locks requires context to be passed from an acquire operation to the corresponding release.Broadly, any context is undesirable and to the extent possible, we might prefer context-free algorithms.In practice, it is common to keep required context in extra fields in the lock body (which can induce increased coherence traffic and increase the size of the lock) or in thread-local storage constructs that track which locks are held by a thread and can also be used to convey context.In managed runtime environments such as the HotSpot Java Virtual Machine, with balanced locking under the "synchronized" construct, such context information can be kept in the stack frame.In C++, context can be kept in std::lock_guard or std::scoped_lock instance, which is typically allocated on stack.Such constructions are an example of the the Resource Acquisition is Initialization(RAII) [47] idiom.And in general, we observe that more flexible locking interfaces that allow context to be easily passed, outside of the lock body, will allow a broader range of lock algorithms to be deployed. Discussion Lessons for locking API designers regarding the interplay between algorithms and interfaces ▶Handoff costs: Under sustained contention, CLH and MCS Release operators can perform handover without any need to access the central shared lock body, via direct threadto-thread communication that does not involve the lock.Reciprocating Locks, however, needs to occasionally consult the central lock arrivals pointer when the entry segment is found to be exhausted and must be reprovisioned.Compared to CLH and MCS, this can increase RMR complexity and generate additional coherence traffic.Interestingly, as we increase the number of contending threads, reciprocating locks will tend to enjoy longer segments and thus need to access the central arrival word less often.In addition, the conditional branch found in the release path of reciprocating locks -which tests whether the successor is nullptr -will tend to be less well-predicted when the segments are shorter.▶ As to why Reciprocating Locks sometimes exceeds the performance of CLH, we make the following observations : Discussion (A) on NUMA systems, the waiting element in Reciprocating Locks is almost surely homed on same NUMA node as the associated thread, providing a performance benefit if home-based snooping is employed.Under CLH, the elements circulate.We note, however, that Reciprocating Locks still tends to outperform CLH on non-NUMA systems, although the difference is lessened. Discussion (B) Reciprocating Locks incurs less indirection and suffers less from stalls arising from address-dependent data loads.Under CLH, the address to be waited upon is not known until after the atomic exchange completes -and the coherence miss from the exchange is satisfied -whereas in Reciprocating Locks the address to be waited upon under contention is known and fixed for the thread. Discussion Similarly, consider the step in CLH before the atomic exchange where a thread clears the flag in the element about to be installed via an atomic exchange.Assuming the implementation of CLH found in Figure 4.14 of [41], thread-local storage contains a pointer to the element, which in turn holds the flag.We find a load from thread-local storage to fetch the address of the element, followed by a dependent store into the element.Under Reciprocating Locks, threadlocal storage simply contains the flag proper, embedded in the WaitingElement, reducing indirection.We thus require just a store to prepare the element.Broadly, CLH requires more indirection because elements circulate.The address of the element to be installed via exchange, and the address of the element to be waited upon will, for a given thread, vary between iterations.In Reciprocating Locks, those addresses are fixed for the thread. Discussion (C) If we tally the minimum number of coherence misses in an idealized contended acquire-release episode, for CLH we have 5 : the store to prepare the element before the exchange; the exchange; the 1st load in the waiting phase after the exchange; the last load in the waiting phase when ownership is passed; and finally, the store in the release operation that conveys ownership.The store to prepare the element, prior to the exchange, causes a coherence miss as the last store to the body of that element was from a different thread, before the element migrated to the thread in question.(This miss occurs outside and before the critical section, but is still undesirable as it causes a stall and consumes interconnect bandwidth).For Reciprocating Locks, in Listing-1, we incur a simple shared→modified coherence upgrade at Line-17 (the line in already in shared state, because of the previous Acquire operation), a miss at Line-20 to exchange the address of the element, a miss at Line-30 when the busy-wait loop condition is ultimately satisfied and ownership is conveyed, and, in the Release operation, a miss at Line-58 when transferring ownership to the successor, for a total of 4 coherence misses.The misses at Line-17 and Line-30 are to memory expected to be homed on the same NUMA node as the thread. Palindromic Admission Schedules Reciprocating Locks may allow a palindromic admission schedule which, under the right circumstances, can persist for long periods. Example Scenario Table-2 illustrates the phenomena with a simple scenario.Threads and all complete for a given lock .Initially, at time 1, is the owner, executing in the critical section, the entry segment is empty and the arrival segment consists of then then then (+++).The noncritical section is empty, so when a thread releases the lock, it immediately recirculates and tries to reacquire. completes the critical section and invokes Release, which, as the entry segment is empty, reverts to and detaches the arrival segment of +++ and moves those threads en-masse to entry segment, and then passes ownership to the head of the entry segment, . recirculates, calls Acquire again, and emplaces itself on the arrival segment, reflecting the state at time 2. Next, releases the lock, and passes ownership to . then calls Acquire and prepends itself to the arrival segment stack, which now contains +, as shown at time 3. releases the lock and conveys ownership to the head of the entry segment, . then recirculates and pushes itself onto the arrival segment, which now holds ++ at time 4. releases , cedes ownership to the head of the entry segment, and then recirculates, adding itself to the arrival segment, now containing +++, at time 5. calls Release and, as the entry segment is empty, detaches the arrival segment of +++, shifting those threads into the arrival segment, and then enables . recirculates and joins the arrival segment, leaving the configuration as seen at time 6. releases the lock and passes ownership to and then joins the arrival segment, as shown at time 7. releases and conveys ownership to , and then prepends itself to the arrival segment, leaving the state as shown at time 8. releases , enables , and then joins the arrival segment, leaving the state as shown at time 9.The states at times 1 and 9 are identical, so the admission schedule repeats with a period length of 8 steps. Long-term Admission Unfairness While there is no long-term starvation, within the admission cycle we see that and are admitted just once while the others thread are admitted twice, which can manifest as long-term relative unfairness between the participating threads.While not a perfect palindrome, we say such a schedule is palindromic and note that the worst case admission unfairness that might manifest by virtue of the lock admission policy is 2 -assuming constant offered load, the most favored thread can be admitted no more than twice as often as the most "unlucky" thread. Cache residency In addition to simple admission, the palindromic schedule introduces an interesting secondary effect related to residual cache residency.We assume a simple system model where all threads circulating over a lock access the same shared last-level cache (LLC). Cache residency While threads are waiting, their residency in the LLC undergoes decay because of the actions of the other threads executing in the critical section or their respective non-critical sections.Arguably, a simple round-robin FIFO FCFS admission schedule results in the worst aggregate miss rate and thus the worst overall throughput. 9.In contrast, the palindromic admission order can result in a better aggregate miss rate in the LLC.Yuan et al. [48] use the term "sawtooth" for the pure palindrome schedule.In our case, the "elements" are threads contending for a lock.Various threads, however, can experience persistent disparate LLC miss rates, yielding a different form of unfairness. Mitigation If desired, we can mitigate the unfairness from the effects above in a number of ways.A simple and expedient approach 9 A simple analogy is sequential single-threaded code where an application needs to iterate over all elements of an array or linked list.A naive approach is to simply access the elements in ascending order until reaching the end, and then repeat, yielding a robin-robin order.Taking residual cache residency in account, however it is better to alternate ascending then descending orders -akin to a classic elevator seek or boustrophedonic order -which yields a palindrome access pattern.Such cache-friendly alternating direction optimizations are well known and appear in various sorting algorithms [45,46] More generally, if we simply pick random elements, without replacement, from the entry segment for succession, we still retain the desirable population bounded anti-starvation property, statistically avoid long-term admission unfairness and cache residency fairness, and continue to enjoy aggregate miss rates (and throughput) that on average are the same or better than classic FIFO.Crucially, as all such reordering is intra-segment, we preserve our bounded bypass property. Conclusion Reciprocating Locks has a fully constant-time doorway phase and a constant-time Release, is practical and fulfills the criteria for general purpose locking 10 .Reciprocating Locks is also architecturally informed as it works well with recent developments in modern NUMA cache-coherent communication fabrics. Conclusion In the future, we plan on exploring the "coherence traffic reduction" optimization (CTR), from HemLock, with Reciprocating Locks.Relatedly, using the Intel CLDEMOTE instruction or non-temporal stores to covey ownership may also act to reduce coherence traffic.Finally, we are exploring techniques to impose long-term statistical admission fairness by means of randomizing or perturbing the order of the entry segment in order to break repeating palindromic admission schedules. 10The name Reciprocating Locks arises from the following analogy with a piston-based compressor or reciprocating pump.The pump's cylinder has distinct intake and exhaust ports and the piston is initially positioned at the bottom of the cylinder.Threads intending to acquire the lock -say, , and where was the first to arrive and last -arrive at the intake port and wait there.On the intake cycle, the piston pulls those threads from the intake port into the cylinder body.On the subsequent exhaust cycle, the piston expels the threads through the exhaust port.Passing through the exhaust port is analogous to passing through the lock's critical section.Like packets of air or gas, the threads are expelled from the cylinder through the exhaust port in an order reversed from that in which they originally arrived : then then .The entry segment corresponds to the current cylinder contents and the arrival segment reflects threads that reside in the intake manifold, before entering the cylinder.The non-critical section is where threads circulate back from the exhaust to the intake.The intake phase is analogous to detaching the current arrival segment and shifting those threads into the entry segment. Figure 1 . Figure 1.MutexBench Figure 2 .Figure 3 . Figure 2. C++ std::atomic<struct> Table 1 . Comparison of lock algorithm properties Table 1 . [13]ode: is the worst-case maximum number of misses to remote memory incurred, under simple sustained contention, by a matching Acquire-Release pair.Misses to remote memory -memory homed on a different NUMA node -may be more expensive than local misses on various platforms, such as modern Intel systems that use the UPI coherence fabric[13], where miss requests are first adjudicated by the home node of the cache line.Algorithms where nodes circulate appear more vulnerable to accumulating such remote misses.For HemLock , we assume simple contention with no multiwaiting.Invalidations per episode: is the number of coherence misses, under sustained contention, experienced by an Acquire-Release episode in a given thread.We empirically approximate that number as follows.Using an ARMv8 system (described below), we modifed the MutexBench microbenchmark to have a degenerate critical section that advanced only a local random number generator and to pass any context from Acquire to Release via thread-local Table 2 . Example of a palindromic admission schedule is to stochastically disrupt or perturb the repeating cycle, which reestablishes statistical long-term fairness.

섹션 본문 59문단 · 54,317자

(제목 없음)

1We present Reciprocating Locks, a novel mutual exclusion locking algorithm, targeting cache-coherent shared memory (CC), that enjoys a number of desirable properties.The doorway arrival phase and the Release operation both run in constant-time.Waiting threads use local spinning and only a single waiting element is required per thread, regardless of the number of locks a thread might hold at a given time.While our lock does not provide strict FIFO admission, it bounds bypass and has strong anti-starvation properties.The lock is compact, space efficient, an d ha s be en intentionally designed to be readily usable in real-world general purpose computing environments such as pthreads, or C++.We show the lock exhibits high throughput under contention and low latency in the uncontended case.Under sustained contention, Reciprocating Locks generate less coherence traffic than MCS and CLH.The performance of Reciprocating Locks is competitive with and often better than the best state-of-the-art scalable queue-based spin locks.

Introduction

2Locks often have a crucial impact on the performance of parallel software, hence they remain the focus of intensive research with a steady stream of algorithms proposed over the last several decades.

The Reciprocating Lock Algorithm

3Briefly, under contention, Reciprocating Locks1 partitions the set of waiting threads into two disjoints lists, which we call the arrival and entry segments.Threads arriving to acquire the lock will push (prepend) themselves onto a stack, using an atomic exchange operation, forming the arrival segment.When the owner releases the lock, it first tries to pass ownership to any threads found in the entry segment.Otherwise, if the entry segment is found empty, the thread then uses an atomic exchange to detach the entire current arrival segment (setting it empty), which then becomes the next entry segment, and then passes ownership to the first element of the entry segment.

4In Reciprocating Locks, a lock instance consists of an arrival word.We deem the lock held if the arrival word is non-zero.Specifically, a value of 0 (nullptr) encodes the unlocked state, 1 (LOCKEDEMPTY) encodes the state of simple locked -locked with an empty arrival segment -and other values encode being locked, where the remainder of the arrival word points to a stack of threads that have recently arrived at the lock and are waiting for admission, forming the arrival segment.

5Threads arriving to acquire the lock use an atomic swap (exchange) operator to install the address of a thread-private waiting element into the arrival word.If the return value from the atomic exchange was nullptr then the arriving thread managed to acquire the lock without contention and can immediately enter the critical section.Otherwise, our thread has encountered contention and must wait.By virtue of the atomic exchange, the thread has managed to push its waiting element onto the arrival segment.The non-nullptr value returned from the atomic exchange identifies the next thread in the stack.Similar to the HemLock [20] and CLH [12,34] lock algorithms, a thread knows only the identity of its immediate neighbor in the arrival segment, and unlike MCS, no explicit linked list of waiting threads is formed or required 2 .That is, the arrival stack is implicit with no next pointer fields in the waiting elements.Our thread then proceeds to local spinning on a flag field within its waiting element.This flag will eventually be set during normal ownership succession by some thread running in the Release operation, passing ownership to our waiting thread.Our thread, still executing in Acquire and now the owner, arranges to convey the address of the next thread in the entry segment, which was obtained from the atomic exchange, to the subsequent corresponding Release operation.The thread identified by that address will subsequently serve as the successor to our current thread.Our thread finally enters the critical section.

6In the corresponding Release operator, if a successor was passed from the corresponding Acquire operator, we simply enable that thread to enter the critical section by setting the flag in its waiting element.Otherwise, we attempt to use an atomic compare_and_exchange (CAS) operation to swing the arrival word from simple locked state back to unlocked.If the CAS was successful then no waiting threads exist and the lock reverts to unlocked state.If the CAS failed, however, additional newly arrived threads must be present on the arrival segment.In that case we employ an atomic exchange to detach the entire arrival segment, leaving the arrival word in simple locked state, encoded as 1.We then pass lock ownership to the first thread in the detached segment by setting the flag in its waiting element.

7Crucially, under contention, threads arrive and join the arrival segment.While the entry segment remains populated, ownership is passed through the entry segment elements in turn.When the current entry segment becomes empty, the Release operator detaches the arrival segment, (via an atomic exchange) which then becomes the next entry segment.Threads migrate, in groups, from the arrival segment to the entry segment.The arrival segment consists of those newly arrived threads currently pushed onto the stack anchored at the arrival word while entry segment reflects a set of threads that have already been detached from the arrival stack.

8The Release operator consults the entry segment firstvia the successor reference passed from Acquire to Release -and passes ownership to the successor if possible.The sequence of successor references passed from Acquire to Release constitutes the entry segment.But if the entry segment is empty -the passed successor argument is nullptr -Release then attempts to replenish the entry segment by detaching the arrival segment, and transferring ownership to the first element.In the event the arrival segment is found empty, the lock reverts to unlocked state. 2 Regarding terminology, say thread arrives and pushes itself onto the stack and then follows.In terms of arrival, is 's predecessor.But in terms of subsequent admission order, in Reciprocating Locks, is 's successor.

There is no such situational distinction between arrival and admission for FIFO

9The arrival segment is implemented by means of a concurrent pop-stack [8], where the key primitives are push and detach-all, which makes our technique immune to the A-B-A pathology [42].By convention, in Reciprocating Locks, only the current lock holder detaches the arrival segment.

10The waiting element is similar to the CLH or MCS "queue node".In our implementation, we opt to place a thread's wait element in thread-local storage (TLS).As a thread can wait on at most one lock at any given time, such a singleton suffices, and tightly bounds memory usage.

11Given that we form a stack for arriving threads, admission order is LIFO within a segment, but remains FIFO between segments.As such, if thread 1 pushes itself onto the arrival segment in Acquire, and then waits, and 2 arrives and pushes itself after 1, then a given thread 2 can bypass or overtake 1 at most once before 1 is next granted ownership, providing thread-specific bounded bypass and thus avoiding indefinite starvation.Alternatively, we could say Reciprocating Locks provides classic -bounded bypass (worst case) where reflects the cardinality of the population of threads that might compete for the lock, yielding population bounded bypass.

Implementation Details

12In Listing-1 we show an implementation of Reciprocating Locks in modern C++.For brevity, this version expresses the critical section as a C++ lambda expression and passes the variables succ and eos from the acquire phase to the corresponding release phase.If desired, it is possible to collapse those into just one variable by a change in encoding.Under a legacy locking interface, with distinct lock() and unlock() operators, context may be passed via extra fields in the lock body or conveyed via thread-local storage.Nonescaping lambdas are efficient and add no particular runtime overhead 3 .The assert statements in the listing express invariants and do not constitute checks against errant usage of the lock.

13We also assume the existence of a "polite" Pause() operator for busy-waiting.For encoding the arrival word, we assume that low-order bit of wait element addresses are 0. We further assume the existence of a wait-free atomic exchange operator.To maintain progress properties, the implementation thereof should not be via loops that employ optimistic compare-and-swap or load-locked and store-conditional primitives.In particular we assume that C++ std::atomic exchange and compare_and_exchange primitives are implemented in a wait-free fashion, as is the case on AMD or Intel x86 processors or ARM processors that support the LSE instruction subset.▶ Simple uncontended Acquire and Release : 1 Thread 1 arrives at Line-14 to acquire lock .'s arrival word is currently nullptr, indicating that is in unlocked state. 2 At Line-17, 1 initializes its thread-specific waiting element, , in anticipation of potential contention. 3 1 then swaps the address of into 1's arrival word in Line-20.The atomic exchange returns nullptr, indicating uncontended acquisition, so control passes into the critical section at Line-47.When the critical section completes execution, control enters the release phase at Line-50. 4 As there are no successors, execution reaches the CAS operation at Line-66.As no additional threads have arrived, the CAS is successful and control returns from Line-66, completing the operation.The CAS reverts the arrival to unlocked state.

14▶ Onset of contention In this scenario we show how to recover from a race in Acquire where a thread pushes its wait element onto the stack but, because of other arriving threads, is not able, in the Release operation, to CAS the arrival word back to 1, and its element becomes "submerged" on the arrival stack.We tolerate this situation by conveying the address of that submerged element through the segment, during succession, allowing us to treat the buried element as the effective end-of-segment (equivalent to nullptr) and otherwise ignore it.We convey that address through the wait element Gate field, when passing ownership.In this case we say we have a zombie terminal element.During succession a thread checks the address of its successor to determine if matches the submerged terminal element. 1 Lock is in unlocked state and thread 1 arrives and acquires the lock. 1 executes the atomic exchange at Line-20 to install the address of its wait element , which we will designate 1, into 's arrival word, the exchange returns 0 (nullptr), so 1 now holds the lock. 1 enters the critical section. 2 Thread 2 now arrives to acquire and exchanges the address of its wait element, 2 into the lock's arrival word. 2's successor is 1 and 2 enters the waiting loop at Line-30. 3 Thread 3 also arrives and pushes the address of its wait element, 3, onto the arrival stack. 3, whose successor is 2, enters the waiting loop at Line-30. 4 1 finishes execution of the critical section and then starts the Release operation.At Line-66, 1 attempts uses a CAS to try to release replacing the address of its 1 with nullptr encoding.The CAS fails, however, as other threads have arrived, and the arrival word now points to 3 instead of 1.At this point, 1's wait element 1 is "buried" or "submerged" in the arrival stack, residing at the distal end. 5 As the CAS failed, control reaches Line-73 where 1 detaches the new arrivals.The atomic exchange replaces 3 with a special LOCKEDEMPTY distinguished value, which indicates the lock is held but that the arrival list is empty and has been previously detached. 6At Line-76, 1 stores its eos (end-of-segment) address, which refers to 1, into 3's Gate field.This both enables 3 and conveys the address of 1 to 3. 1 has completed is locking episode. 7 3, at Line-30, observes that its Gate field is now 1.Its local eos variable now refers to 1. 3 now has ownership.The comparison at Line-37 does not match, so 3 enters the critical section. 8 3 executes the critcal section.Upon return from the critical section, 3 at Line-53, recognizes that it has a successor, 2 (2), on the detached entry segment.At Line-58, 3 stores its eos value, 1, into 2's Gate field.The store conveys both the identity of the end-of-segment and ownership. 3 has finished its locking episode and returns at line-59. 9 2 observes at Line-30 that is has received ownership, and its eos value is now 1. 2's indicated successor is 1 (1) and the comparsion at Line-37 matches, so we have reached the end of the detached entry segment. 2 then clears its local succ successor pointer and sets its local eos value to LOCKEDEMPTY. 10 2 enters and executes the critical section. 11Control in 2 reaches line-66, where the CAS succeeds and swings the arrival word from LOCKEDEMPTY to unlocked.

15We note that a contended Release operation might need to execute two atomic operations, the CAS at Line-66 and the exchange at Line-76, potentially increasing RMR complexity [4,7].In practice, given the narrow window, the underlying cache line tends remain to local modified state.If desired, to mitigate this concern, we could condition the CAS on an immediate prior load, reducing the number of futile CAS operations.We found this optimization provided no observable benefit, and did not use it.

16In the case where is submerged, we use 's address for addressed-based comparisons (Line-37) as a distinguished marker or sentinel to indicate the logical end-of-segment. itself, however, will not be subsequently accessed by succession within the segment.Elements associated with a given thread can appear on at most one segment at any time, but, when an address is used as an end-of-segment marker, it is possible that it appears on both the arrival segment and entry segment.

17We observe that the eos value could also reside in a field the lock body, potentially sequestered and isolated on a dedicated cache line, instead of in the waiting elements.While viable, that approach increases the size of the lock body, and increases induced coherence traffic.Instead, we borrow a technique from Compact NUMA-Aware Locks (CNA) [17] and avoid such shared central fields by propagating information -in this case the address of the terminal element of the segment -through the chain of waiting elements.

18Terminus, end-of-segment, eos, marker, sentinel, ghost, zombie, alternative end, Vesper, punctuation, virtual, phantom end mark, tombstone, section mark; pilcrow, fleuron, hedera, dinkus, -30-Eos; end-of-segment; terminus; Vesper; Astraeus; fini; Boustrophedonic ▶ Sustained contention 1 Lock is initially in unlocked state.Thread 1 arrives to acquire . 1's exchange operation at Line-20 installs the address of 1's wait element, 1, into 's arrival word.As the exchange returned nullptr, 1 has acquired the lock. 2 1 enters and executes the critical section. 3While 1 holds , thread 2 arrives and 2 pushes onto the arrival stack.The exchange operation at Line-20 returns 1 into 2's local tail variable.As tail is non-0, 2 must wait at Line-29. 2 local succ variable refers to 1. 4 With 1 still holding , 3 also arrives and uses the atomic exchange to push its element 3 onto the arrival stack.The exchange returns 2 and 3's succ variable points to 2.The arrival stack consists of 3 followed by 2 followed by 1, although 1 is "buried" and will be excised during subsequent succession.The entry segment is empty. 3 waits on 3 at Line-30 5 Similarly, 4 arrives and pushes 4 onto the arrival stack and then waits. 4's successor variable points to 3. 6 1 eventually completes the critical section and then executes the Release phase at Line-50.As 1's succ variable is nullptr, indicating an empty entry segment, 1 then attempts the CAS, at Line-66 which fails. 1 then executes exchange(LOCKEDEMPTY) to detach the arrival segment at Line-73.The exchange operator returns 4.The arrival segment is now empty and the entry segment consists of 4 then 3 then 2 then 1. 1 passes ownership to 4 at Line-76, passing the address of 1 as the end-of-segment marker. 7 4 is now the owner and departs its waiting phase at Line-31, having received 1 as the end-of-segment address.The end-of-segment address check at Line-37 does not match, so 4 enters the critical section. 8while 4 holds , 5 and then 6 arrive to acquire , pushing 5 and then 6, respectively, onto the arrival stack.The arrival segment consists of 6 then 5 and the detached entry segment is just 3 and 2 and 1.When 5 arrived, its exchange replaced LOCKEDEMPTY with 5.Crucially, Line-25 converted LOCKEDEMPTY, which is encoded as 1, to a effective successor value of nullptr. 9 4 releases the lock.As 3 is 4's the successor, we grant ownership to 3 at Line-58, again passing 1 as the end-of-segment address. 10 3 departs its wait phase at Line-31 and enters and executes the critical section. 11 3 releases the lock, observing 2 as its successor and grants ownership to 2 at Line-58, again, passing 1 as the end-of-segment, 12 2 departs its wait phase at line-31.In this particular step, the address check at Line-37 matches, and 2 annuls its succ variable and sets its eos to LOCKEMPTY.We have reached the end of the entry segment, which is now exhausted. 2 enters and executes the critical section. 13 2 executes the release phase, and since succ is nullptr at Line-53, the current entry segment is empty. 2 then attempts the CAS at line 66, which tries to replace LOCKEDEMPTY with unlocked.The CAS fails as the arrival segment is populated with 6 and 5 and the arrival word points to 6. 2 then detaches the new arrivals at Line-73 and passes ownership to 6 (via 6) at Line-76, and also conveying the end-of-segment address, which is now LOCKEDEMPTY, to 6. 14 6 exits the waiting loop at Line-30, noting that eos is now LOCKEDEMPTY. 6's successor is 5. 6 enters the critical section. 15 6 completes the critical section and executes the release phase.As 6's succ variable refers to 5, we pass ownership and the end-of-segment address (LOCKEDEMPTY at this juncture) to 5. 16 5 recognizes ownership at Line-30 and then enters the critical section at Line-47. 17 5 releases the lock.It's succ value is nullptr to it the attempts the CAS at Line-66.In this case the CAS succeeds, replacing LOCKEDEMPTY with the unlocked encoding of nullptr. is restored to unlocked state.

Additional Requirements

19practical; pragmatic; de facto; QoI = quality of implementation, desiderata

20We target lock algorithms that are suitable for environments such as the Linux kernel, as a replacement for the user-level pthreads_mutex primitive, or for use in runtime environments such as the HotSpot Java Virtual Machine (JVM), which is written in C++.As such, we identify additional de-facto requirements for general purpose lock algorithms.Safe Against Prompt Lock Destruction Various lock algorithms perform stores in the Release operation that potentially release ownership, but then perform additional accesses to fields in the lock body to ensure succession and progress.This can result in a class of unsafe use-after-free memory reference errors [9,37].A detailed description of such an error can be found in [20].All algorithms for use in the linux kernel or in the pthreads environment are expected to be prompt lock destruction safe.Support for Large Numbers of Extant Threads The algorithms must support the simultaneous participation of an arbitrary number of threads, where threads are created and destroyed dynamically, and the peak number of extant threads is not known in advance.Support for Large Numbers of Extant Locks Similarly, the algorithm needs to support large numbers of lock instances, which can be created and destroyed dynamically.Recent work [32] shows the Linux kernel has more than 6000 statically initialized lock instances.Again, the number of locks is not know in advance, as drivers load, and unload, for instance, or as data structures containing locks dynamically resize.Plural Locking A given thread is expected to be able to lock and hold a large number of locks simultaneously.In the Linux kernel, for instance, situations arise when 40 or more distinct locks are held by a single thread at a given time, as evidenced by the MAX_LOCK_DEPTH tunable, which is used by the kernel's "lockdep" facility to track the set of locks held in an explicit per-thread list for the purposes of detecting potential deadlock.Furthermore, locks must be able to be released in non-LIFO imbalanced order as it is fairly common to acquire a lock in one routine, return, and then release the lock in the caller.

Space Efficient

21We expect the lock algorithm to be frugal and parsimonious with regard to space usage.Critically, any algorithms that require per-lock and per-thread storage -with ℎ * space consumption -such as Anderson's Array-Based Queue Lock [6], are not suitable.FIFO as a non-goal We also note that many real-world lock implementations, such as the current implementation of Java's "synchronized" in the HotSpot Java Virtual Machine, the java.util.Concurrent.ReentrantLock, and the default pthread_mutex on Linux, are non-FIFO, and in fact permit unbounded bypass and indefinite starvation.Relatedly, Compact NUMA-Aware Locks (CNA) [17] intentionally imposes non-FIFO admission order to improve throughput on NUMA platforms, trading aggregate throughput against strict FIFO ordering.In fact, strict FIFO locking is an antipattern for common practical lock designs, as it suffers from reduced throughput compared to more relaxed admission schedules, and has shortcomings when used with waiting techniques that deschedule threads, or when involuntary preemption is in play [16,19].Forgoing strict FIFO admission schedules allows more opportunism that in some circumstances may translate into improved throughput.

22Given these particular constraints, we exclude a number of algorithms from consideration.Dvir's algorithms [23], Rhee's algorithm [40], Lee's HL1 and HL2 [30,31], and Jayanati's "Ideal Queued Spinlock" [28] [29] algorithms, when simplified for use in cache-coherent (CC) environments, all have extremely simple and elegant paths and low RMR complexity, suggesting they would be competitive and good candidates, but they do not readily tolerate multiple locks being held simultaneously.The above tend to use so-called "nodetoggling" and "node-switching" techniques -also called "two-face" by Lee -that, while they work well when a thread holds at most one lock, are awkward for general purpose use.Our specific concerns are space blow-up due to the need to maintain toggle element pairs and a "face" index for pairs of locks and threads, in addition to the requirement that we re-associate that metadata with the lock instance at releasetime.Some of Dvir and Lee's algorithms are also not safe against prompt lock destruction.

Related Work

23While mutual exclusion remains an active research topic [1-3, 12, 15-18, 22-24, 26-29, 36, 39, 41] we focus on locks closely related to our design.

24Simple test-and-set or polite test-and-test-and-set [41] locks are compact and exhibit excellent latency for uncontended operations, but fail to scale and may allow unfairness and even indefinite starvation.Ticket Locks are compact and FIFO, and also have excellent latency for uncontended operations, but they also fail to scale because of global spinning, although some variations attempt to overcome this obstacle, at the cost of increased space [18,38].For instance, Anderson's array-based queueing lock [5,6] is based on Ticket Locks but provides local spinning.It employs a waiting array for each lock instance, sized to ensure there is at least one array element for each potentially waiting thread, yielding a potentially large footprint.The maximum number of participating threads must be known in advance when initializing the lock.TWA [18] is a variation on ticket locks that reduces the incidence of global spinning.

25Queue-based locks such as MCS or CLH are FIFO and provide local spinning and are thus more scalable.MCS is used in the linux kernel for the low-level "qspinlock" construct [10,11,33].Modern extensions of MCS edit the queue order to make the lock NUMA-Aware [17].MCS readily allows editing and re-ordering of the queue of waiting threads, [15,17,35] whereas editing the chain is more difficult under CLH, HemLock and Reciprocating Locks, where there are no explicit linked lists.

26CLH is extremely simple, has excellent RMR complexity, and requires just an single atomic exchange operation in the Acquire operation and no atomic read-modify-write instructions in Release.Unfortunately the waiting elements migrate between threads, which may be inimical to performance in NUMA environments.CLH locks also require explicit constructors and destructors, which may be inconvenient 4 .Our specific implementation uses a variation on Scott's [41] Figure 4.14, which converts the CLH lock to be context-free [44], adhering to a simple programming interface that passes just the address of the lock, albeit at the cost of adding an extra field to the lock body to convey the address of the head waiting element to Release.

27HemLock combines aspects of both CLH and MCS to form a lock that has very simple waiting node lifecycle constraints, is context-free but still scales well in common usage scenarios.HemLock does not provide constant remote memory reference (RMR) complexity [23] in scenarios where a thread holds multiple contended locks.In this situation the single node suffers from multi-waiting [20].Similar to MCS, Hem-Lock lacks a constant-time unlock operation, whereas the unlock operator for CLH and Tickets is constant-time.Unlike MCS, HemLock requires active synchronous back-and-forth communication in the unlock path between the outgoing thread and its successor to protect the lifecycle of the waiting 4 Many lock implementations require just trivial constructors to set the lock fields to 0 or some constant, and trivial destructors, which do nothing.The Linux kernel spinlock_t/qspinlock_t interface provides a constructor, but does not even expose a destructor.Similarly, C++ std::mutex is allowed to be trivially destructible, meaning storage occupied by trivially destructible objects may be reused without calling the destructor.Under both GCC g++ version 13 and Clang++ Version 18, is_trivially_destructible reports True for std::mutex, and as such, destructors do not run.This situation could be rectified by recompiling, but we would also need to recompile all libraries transitively depended on by the application, including those deployed in shared libraries in binary-only form on the system.element.We note, however, that HemLock remains constanttime in the Release operator to the point where ownership is conveyed to the successor.HemLock uses address-based transfer of ownership, writing the address of the lock instead of a boolean, differentiating it from MCS and CLH.Reciprocating Locks, like HemLock, requires just a singleton per-thread waiting element allocated in thread-local storage.

28We opted to exclude NUMA-aware locks such as Cohort Locks [21,22] and Compact NUMA-Aware Locks (CNA) [17] from consideration.We excluded Fissile Locks and GCR [16] as they have lax time-based anti-starvation mechanism.Fissile, specifically, depends on the owner of the inner lock to make progress to monitor for starvation.

29In Table-1 we compare the attributes of various local algorithms.Red -colored cells indicate potential undesirable properties.Note that all the locks provide a constant-time doorway phase.In the following we explain the meaning of each property.

30Spinning: reflects whether the lock utilizes local, global or semi-local [20] spinning.Constant-time Unlock: indicates if the lock Release operation is bounded.As noted above, HemLock is constant-time up to the point where the lock is either released or transferred to a successor, but the Release operator, for reasons of memory safety, then waits for the successor to acknowledge transfer of ownership before the memory underlying the queue element can be potentially reused.Specifically, in HemLock an uncontended Release operation is constant-time and a contended Release is constant-time up to and including the point where ownership is conveyed to the successor.FIFO: indicates the lock provides strict FIFO admission.Context-free: indicates additional information does not need to be transferred from the lock operator to the corresponding Release operation.Path Complexity -Acquire and Path Complexity -Release : we measured the size of the Acquire and Release methods in units of platform independent LLVM intermediate representation (IR) instructions, as emitted by clang++-18, which serves as a simple measure for path complexity.We note that much of the complexity found in TWA manifests through the use of the hash function which maps lock address and ticket value pairs to slots in the waiting array.On-Stack: indicates the queue elements, if any, may be allocated on-stack.This also implies the nodes do not migrate and have a tenure constrained to the duration of the locking episode.Nodes Circulate: queue elements migrate between threads.This often implies the need for an explicit queue element lifecycle management system and precludes convenient on-stack allocation of queue elements.Migration may also be unfriendly to performance in NUMA environments.Explicit CTOR/DTOR Required: indicates the lock requires non-trivial constructors or destructors.CLH, for instance, requires destructors to run to release the wait elements referenced in the lock, to avoid memory leaks.Maximum Remote Misses per We used the ARM l2d_cache_inval hardware performance counter, which tallies L2 cache invalidation events, as simple proxy for coherence traffic -both latency and bandwith.We report the number of l2d_cache_inval events per episode.

31As can be seen, Reciprocating Locks is parsimonious and incurs just 4 invalidations per episode, while CLH requires 5 5 .Ticket locks require (10 in our example) invalidations per episode, where is the number of participating threads, given the global spinning.The number of misses incurred by CLH, MCS, HemLock and Reciprocating Locks is constant and not a function of the number of threads.These empirically-derived results align closely with a static analysis of the code and the expected number of coherence misses in the Acquire and Release paths.Space Complexity: reflects the space complexity of the lock algorithm where is the number of active threads, is the number of extant locks, is the number of locks currently held plus the number of threads currently waiting on locks, is the size of the waiting element. is the size of a lock instance.When a lock algorithm requires context to be passed from Acquire to the corresponding Release, we set to 2 to indicate that our implementation allocated an extra word in the lock body to pass such information.Implementations that require context can avoid that space requirement in the lock body if they opt to pass context information by other means, such as via thread-local storage, in which case would be 1.HemLock is context-free, so the per-lock space usage is just 1, while Ticket Locks and TWA require 2 words per lock.TWA requires an additional 4096 words for the global waiting table that is shared over all thread and lock instances. 5We observed similar ratios with performance counters that reported the number of "snoop" messages, and on Intel by counting OFFCORE requests.We also observed in passing, while examining data from hardware performance counters, that CLH and MCS suffered from more stalls (both event counts and duration) from misses than did Reciprocating locks.CLH in particular executes a dependent load in the critical path in the arrival doorway on the address returned from the atomic exchange.The address to be loaded from is not known until after the exchange returns, denying the processor the ability to speculate or execute out-of-order.

Empirical Performance Results

32Unless otherwise noted, all data was collected on an Oracle X5-2 system system having 2 sockets, each populated with an Intel Xeon E5-2699 v3 CPU running at 2.30GHz.Each socket has 18 cores, and each core is 2-way hyperthreaded, yielding 72 logical CPUs in total.The system was running Ubuntu 20.04 with a stock Linux version 5.4 kernel, and all software was compiled using the provided GCC version 9.3 toolchain at optimization level "-O3".64-bit C or C++ code was used for all experiments.Factory-provided system defaults were used in all cases, and Turbo mode [43] was left enabled.In all cases default free-range unbound threads were used, with no pinning of threads to processors.At above 18 ready threads, the kernel starts to place additional threads onto the second socket, and NUMA effects come into play.We implemented all user-mode locks within LD_PRELOAD interposition libraries that expose the standard POSIX pthread_ mutex_t programming interface using the framework from [22].This allows us to change lock implementations by varying the LD_PRELOAD environment variable and without modifying the application code that uses locks.The C++ std::mutex construct is implemented directly via pthread_ mutex primitives, so interposition works for both C and C++ code.All lock busy-wait loops on Intel used the PAUSE instruction and YIELD on ARMv8.To reduce false sharing, all waiting elements were aligned and sequestered at 128-byte boundaries, and, for the "MutexBench" benchmarks, below, the lock instances where similarly sequestered.For the CLH, MCS, and Reciprocating Locks implementations used in the benchmark section of this paper, we elected to pass any additional context information via extra fields in the lock instance.

MutexBench benchmark

33The MutexBench benchmark spawns concurrent threads.Each thread loops as follows: acquire a central lock L; execute a critical section; release L; execute a non-critical section.At the end of a 10 second measurement interval the benchmark reports the total number of aggregate iterations completed by all the threads.We report the median of 7 independent runs in Figure -1a where the critical section advances a shared global std::mt19937 Mersenne Twister pseudo-random number generator (PRNG) one step, and the non-critical section is empty, subjecting the lock to extreme contention.(At just one thread, this configuration also constitutes a useful benchmark for uncontended latency).The -axis reflects the number of concurrently executing threads contending for the lock, and the -axis reports aggregate throughput.For clarity and to convey the maximum amount of information to allow a comparison of the algorithms, the -axis is offset to the minimum score and the -axis is logarithmic.

34We ran the benchmark under the following lock algorithms: MCS is classic MCS.To avoid memory allocation during the measurement interval, the MCS implementation uses a thread-local stack of free queue elements.CLH is CLH based on Scott's CLH variant with a standard interface Figure-4.14 of [41]; For the MCS and CLH locks, our implementation stores the current head of the queue -the owner -in a field adjacent to the tail, so the lock body size was 2 words.CLH presents something of a challenge when used under the pthread_mutex interface.First, pthreads allows the programmer to use trivial initializers -setting the mutex body to all 0 -and avoid calling pthread_mutex_init.To compensate, we modified pthread_mutex_lock to populate such an uninitialized lock with the CLH "dummy node" lazily, ondemand, on the first lock operation.In pthread_mutex_destroy we free the node, if populated, but many applications also do not call pthread_mutex_destroy, which constitutes a memory leak.As such, to allow CLH to be included, we avoided applications that create and then abandon large numbers of locks in a dynamic fashion.Ticket is a classic Ticket Lock; HemLock is the HemLock algorithm, with the CTR (coherence traffic reduction) optimization.

35In Figure-1a we make the following observations regarding operation at maximal contention with an empty critical section:

36• At 1 thread the benchmark measures the latency of uncontended Acquire and Release operations.Ticket Locks are the fastest, followed closely by HemLock, Reciprocating Locks, CLH and MCS.• As we increase the number of threads, Ticket Locks initially do well but then fade, exhibiting a precipitous drop in performance.TWA is the clear leader in the "middle" area of the graph, between 4 and 16 threads.• Broadly, at higher thread counts, HemLock performs slightly better than or the same as CLH or MCS, while Reciprocating Locks provides the best throughput.

37In Figure-1b we pass arguments to MutexBench that configure it to implement a delay in the non-critical section.Each thread has a private std::mt19937 pseudo-random number generator.The non-critical section generates, using the private PRNG, a uniform random number in the range [0−250) and then advances its private PRNG that many steps.(We take care to make sure this operation can not be optimized away by consuming the PRNG value at the end of the thread's run).As above, the critical section advances the shared PRNG one step.As can be seen, we enjoy positive scalability up to about 5 threads.At higher thread counts, Reciprocating Locks manages to exhibit the least reduction in scalability.

38In Figure -1c and Figure -1d, we show the results of Mu-texBench on an ARMv8 (aarch64) system, showing that the relative performance of the various algorithms remains portable over disparate architectures.The ARMv8 system was an Ampere Altra Max NeoVerse-N1 with 128 processors on a single socket and was running Ubuntu 24.04.We compiled all code using the -mno-outline-atomics -march= armv8.2-a+lseflags in order to allow direct use of modern atomic exchange, CAS and fetch-and-add instructions instead of the legacy LL-SC (load-locked store-conditional) forms thereof.

std::atomic

39In Figure -2a, our C++ atomic exchange benchmark defines a simple structure type S that contains 5 32-bit integers.Each thread declares a local S instance, and we also declare a shared global std::atomic<S> A {}.The C++ compiler and runtime implement std::atomic for such objects by hashing the address of the instance into an array of mutexes, and acquiring those as needed to implement the desired atomic action.Each thread loops for 10 seconds, using std::atomic<S>::exchange to swap its local copy with the shared global, and we then report aggregate throughput rate, in terms of completed exchange operations, at the end of the measurement interval.The figure depicts the median score of 7 runs and the overall ranking of the locks is similar to that observed under MutexBench.Figure-2b is similar, but instead of std::atomic:exchange, we use std::atomic:load to fetch the shared global, make a local copy, increment the 1st of the five constituent integer fields in that copy, and then call std::atomic:compare_ exchange_strong (CAS) in an inner loop to try replace the global copy with the updated local version.The load operator acquires and releases all necessary covering locks, as does the compare_exchange_strong operator.If the CAS fails, we update our fresh local copy (returned from CAS) and retry.At the end of the 10 second measurement interval we report total number of successful CAS operations.The graph reports the median score of 7 runs.For both benchmarks, the relative ranks of the various lock algorithms remains similar to what was observed with MutexBench.

LevelDB

40In Figure-3 we used the "readrandom" benchmark in Lev-elDB version 1.20 database6 varying the number of threads and reporting throughput from the median of 5 runs of 50

Discussion

41▶Constant-time arrival doorway and Release paths, as a consequence of having desirable progress properties, may yield more predictable performance.Furthermore, such designs are more inherently amenable to "polite" waiting, where a thread voluntarily deschedules itself and explicitly waits to be notified of transfer of ownership, by means of thread identity-based waiting primitives, such as park-unpark [14] or address-based waiting, such as the linux futex [25] primitive, which underlies the pthreads synchronization services.Use of such primitives allows the implementation to avoid toxic waiting policies, such as unbounded busy-waiting; periodic polling via timed sleep operations; or operating-system advisory yield calls.Specifically, having constant-time paths means contending threads wait on only one conditiontransfer of ownership -and have one waiting phase.In contrast, locks such as MCS or HemLock may need to wait on additional conditions.▶Lifecycle management : In classic MCS the address of the owner's "queue node" must be passed from an acquire operation to the corresponding release.Relatedly, that queue node must remain extant during the entire acquire-release period, and can not be use for other locking operations.In Reciprocating Locks, the element needs to remain extant only for the duration of the acquire operation, affording the implementer more latitude as to how and where the element is allocated.A singleton element allocated in thread-local storage suffices.▶Passing of context from acquire to release : Like MCS and CLH, Reciprocating Locks requires context to be passed from an acquire operation to the corresponding release.Broadly, any context is undesirable and to the extent possible, we might prefer context-free algorithms.In practice, it is common to keep required context in extra fields in the lock body (which can induce increased coherence traffic and increase the size of the lock) or in thread-local storage constructs that track which locks are held by a thread and can also be used to convey context.In managed runtime environments such as the HotSpot Java Virtual Machine, with balanced locking under the "synchronized" construct, such context information can be kept in the stack frame.In C++, context can be kept in std::lock_guard or std::scoped_lock instance, which is typically allocated on stack.Such constructions are an example of the the Resource Acquisition is Initialization(RAII) [47] idiom.And in general, we observe that more flexible locking interfaces that allow context to be easily passed, outside of the lock body, will allow a broader range of lock algorithms to be deployed.

42Lessons for locking API designers regarding the interplay between algorithms and interfaces ▶Handoff costs: Under sustained contention, CLH and MCS Release operators can perform handover without any need to access the central shared lock body, via direct threadto-thread communication that does not involve the lock.Reciprocating Locks, however, needs to occasionally consult the central lock arrivals pointer when the entry segment is found to be exhausted and must be reprovisioned.Compared to CLH and MCS, this can increase RMR complexity and generate additional coherence traffic.Interestingly, as we increase the number of contending threads, reciprocating locks will tend to enjoy longer segments and thus need to access the central arrival word less often.In addition, the conditional branch found in the release path of reciprocating locks -which tests whether the successor is nullptr -will tend to be less well-predicted when the segments are shorter.▶ As to why Reciprocating Locks sometimes exceeds the performance of CLH, we make the following observations :

43(A) on NUMA systems, the waiting element in Reciprocating Locks is almost surely homed on same NUMA node as the associated thread, providing a performance benefit if home-based snooping is employed.Under CLH, the elements circulate.We note, however, that Reciprocating Locks still tends to outperform CLH on non-NUMA systems, although the difference is lessened.

44(B) Reciprocating Locks incurs less indirection and suffers less from stalls arising from address-dependent data loads.Under CLH, the address to be waited upon is not known until after the atomic exchange completes -and the coherence miss from the exchange is satisfied -whereas in Reciprocating Locks the address to be waited upon under contention is known and fixed for the thread.

45Similarly, consider the step in CLH before the atomic exchange where a thread clears the flag in the element about to be installed via an atomic exchange.Assuming the implementation of CLH found in Figure 4.14 of [41], thread-local storage contains a pointer to the element, which in turn holds the flag.We find a load from thread-local storage to fetch the address of the element, followed by a dependent store into the element.Under Reciprocating Locks, threadlocal storage simply contains the flag proper, embedded in the WaitingElement, reducing indirection.We thus require just a store to prepare the element.Broadly, CLH requires more indirection because elements circulate.The address of the element to be installed via exchange, and the address of the element to be waited upon will, for a given thread, vary between iterations.In Reciprocating Locks, those addresses are fixed for the thread.

46(C) If we tally the minimum number of coherence misses in an idealized contended acquire-release episode, for CLH we have 5 : the store to prepare the element before the exchange; the exchange; the 1st load in the waiting phase after the exchange; the last load in the waiting phase when ownership is passed; and finally, the store in the release operation that conveys ownership.The store to prepare the element, prior to the exchange, causes a coherence miss as the last store to the body of that element was from a different thread, before the element migrated to the thread in question.(This miss occurs outside and before the critical section, but is still undesirable as it causes a stall and consumes interconnect bandwidth).For Reciprocating Locks, in Listing-1, we incur a simple shared→modified coherence upgrade at Line-17 (the line in already in shared state, because of the previous Acquire operation), a miss at Line-20 to exchange the address of the element, a miss at Line-30 when the busy-wait loop condition is ultimately satisfied and ownership is conveyed, and, in the Release operation, a miss at Line-58 when transferring ownership to the successor, for a total of 4 coherence misses.The misses at Line-17 and Line-30 are to memory expected to be homed on the same NUMA node as the thread.

Palindromic Admission Schedules

47Reciprocating Locks may allow a palindromic admission schedule which, under the right circumstances, can persist for long periods.

Example Scenario

48Table-2 illustrates the phenomena with a simple scenario.Threads and all complete for a given lock .Initially, at time 1, is the owner, executing in the critical section, the entry segment is empty and the arrival segment consists of then then then (+++).The noncritical section is empty, so when a thread releases the lock, it immediately recirculates and tries to reacquire. completes the critical section and invokes Release, which, as the entry segment is empty, reverts to and detaches the arrival segment of +++ and moves those threads en-masse to entry segment, and then passes ownership to the head of the entry segment, . recirculates, calls Acquire again, and emplaces itself on the arrival segment, reflecting the state at time 2. Next, releases the lock, and passes ownership to . then calls Acquire and prepends itself to the arrival segment stack, which now contains +, as shown at time 3. releases the lock and conveys ownership to the head of the entry segment, . then recirculates and pushes itself onto the arrival segment, which now holds ++ at time 4. releases , cedes ownership to the head of the entry segment, and then recirculates, adding itself to the arrival segment, now containing +++, at time 5. calls Release and, as the entry segment is empty, detaches the arrival segment of +++, shifting those threads into the arrival segment, and then enables . recirculates and joins the arrival segment, leaving the configuration as seen at time 6. releases the lock and passes ownership to and then joins the arrival segment, as shown at time 7. releases and conveys ownership to , and then prepends itself to the arrival segment, leaving the state as shown at time 8. releases , enables , and then joins the arrival segment, leaving the state as shown at time 9.The states at times 1 and 9 are identical, so the admission schedule repeats with a period length of 8 steps.

Long-term Admission Unfairness

49While there is no long-term starvation, within the admission cycle we see that and are admitted just once while the others thread are admitted twice, which can manifest as long-term relative unfairness between the participating threads.While not a perfect palindrome, we say such a schedule is palindromic and note that the worst case admission unfairness that might manifest by virtue of the lock admission policy is 2 -assuming constant offered load, the most favored thread can be admitted no more than twice as often as the most "unlucky" thread.

Cache residency

50In addition to simple admission, the palindromic schedule introduces an interesting secondary effect related to residual cache residency.We assume a simple system model where all threads circulating over a lock access the same shared last-level cache (LLC).

51While threads are waiting, their residency in the LLC undergoes decay because of the actions of the other threads executing in the critical section or their respective non-critical sections.Arguably, a simple round-robin FIFO FCFS admission schedule results in the worst aggregate miss rate and thus the worst overall throughput. 9.In contrast, the palindromic admission order can result in a better aggregate miss rate in the LLC.Yuan et al. [48] use the term "sawtooth" for the pure palindrome schedule.In our case, the "elements" are threads contending for a lock.Various threads, however, can experience persistent disparate LLC miss rates, yielding a different form of unfairness.

Mitigation

52If desired, we can mitigate the unfairness from the effects above in a number of ways.A simple and expedient approach 9 A simple analogy is sequential single-threaded code where an application needs to iterate over all elements of an array or linked list.A naive approach is to simply access the elements in ascending order until reaching the end, and then repeat, yielding a robin-robin order.Taking residual cache residency in account, however it is better to alternate ascending then descending orders -akin to a classic elevator seek or boustrophedonic order -which yields a palindrome access pattern.Such cache-friendly alternating direction optimizations are well known and appear in various sorting algorithms [45,46] More generally, if we simply pick random elements, without replacement, from the entry segment for succession, we still retain the desirable population bounded anti-starvation property, statistically avoid long-term admission unfairness and cache residency fairness, and continue to enjoy aggregate miss rates (and throughput) that on average are the same or better than classic FIFO.Crucially, as all such reordering is intra-segment, we preserve our bounded bypass property.

Conclusion

53Reciprocating Locks has a fully constant-time doorway phase and a constant-time Release, is practical and fulfills the criteria for general purpose locking 10 .Reciprocating Locks is also architecturally informed as it works well with recent developments in modern NUMA cache-coherent communication fabrics.

54In the future, we plan on exploring the "coherence traffic reduction" optimization (CTR), from HemLock, with Reciprocating Locks.Relatedly, using the Intel CLDEMOTE instruction or non-temporal stores to covey ownership may also act to reduce coherence traffic.Finally, we are exploring techniques to impose long-term statistical admission fairness by means of randomizing or perturbing the order of the entry segment in order to break repeating palindromic admission schedules. 10The name Reciprocating Locks arises from the following analogy with a piston-based compressor or reciprocating pump.The pump's cylinder has distinct intake and exhaust ports and the piston is initially positioned at the bottom of the cylinder.Threads intending to acquire the lock -say, , and where was the first to arrive and last -arrive at the intake port and wait there.On the intake cycle, the piston pulls those threads from the intake port into the cylinder body.On the subsequent exhaust cycle, the piston expels the threads through the exhaust port.Passing through the exhaust port is analogous to passing through the lock's critical section.Like packets of air or gas, the threads are expelled from the cylinder through the exhaust port in an order reversed from that in which they originally arrived : then then .The entry segment corresponds to the current cylinder contents and the arrival segment reflects threads that reside in the intake manifold, before entering the cylinder.The non-critical section is where threads circulate back from the exhaust to the intake.The intake phase is analogous to detaching the current arrival segment and shifting those threads into the entry segment.

Figure 1 .

55Figure 1.MutexBench

Figure 2 .Figure 3 .

56Figure 2. C++ std::atomic<struct>

Table 1 .

57Comparison of lock algorithm properties

58[13]ode: is the worst-case maximum number of misses to remote memory incurred, under simple sustained contention, by a matching Acquire-Release pair.Misses to remote memory -memory homed on a different NUMA node -may be more expensive than local misses on various platforms, such as modern Intel systems that use the UPI coherence fabric[13], where miss requests are first adjudicated by the home node of the cache line.Algorithms where nodes circulate appear more vulnerable to accumulating such remote misses.For HemLock , we assume simple contention with no multiwaiting.Invalidations per episode: is the number of coherence misses, under sustained contention, experienced by an Acquire-Release episode in a given thread.We empirically approximate that number as follows.Using an ARMv8 system (described below), we modifed the MutexBench microbenchmark to have a degenerate critical section that advanced only a local random number generator and to pass any context from Acquire to Release via thread-local

Table 2 .

59Example of a palindromic admission schedule is to stochastically disrupt or perturb the repeating cycle, which reestablishes statistical long-term fairness.

참고문헌 30건

  1. Multiprocessor Synchronization Primitives with Priorities IFAC Proceedings Volumes · Elsevier BV · 1991 10.1016/s1474-6670(17)51259-8
  2. Lock Cohorting ACM Transactions on Parallel Computing · Association for Computing Machinery · 2015 10.1145/2686884
  3. Tight RMR lower bounds for mutual exclusion and other problems 2008 10.1145/1374376.1374410
  4. Scalable reader-writer synchronization for shared-memory multiprocessors 1991 10.1145/109625.109637
  5. The performance of spin lock alternatives for shared-money multiprocessors IEEE Transactions on Parallel and Distributed Systems · Institute of Electrical and Electronics Engineers · 1990 10.1109/71.80120
  6. Shared-memory mutual exclusion: major research trends since 1986 Distributed Computing · Springer Science+Business Media · 2003 10.1007/s00446-003-0088-6
  7. Transformations of Mutual Exclusion Algorithms from the Cache-Coherent Model to the Distributed Shared Memory Model 2005 10.1109/icdcs.2005.83
  8. Queue locks on cache coherent multiprocessors 2002 10.1109/ipps.1994.288305
  9. Modeling critical sections in Amdahl's law and its implications for multicore design 2010 10.1145/1815961.1816011
  10. Optimizing a FIFO, scalable spin lock using consistent memory 2002 10.1109/real.1996.563705
  11. Lock cohorting 2012 10.1145/2145816.2145848
  12. Be my guest 2016 10.1145/2851141.2851160
  13. Extending Amdahl’s Law for Multicores with Turbo Boost IEEE Computer Architecture Letters · Institute of Electrical and Electronics Engineers · 2015 10.1109/lca.2015.2512982
  14. Malthusian Locks 2017 10.1145/3064176.3064203
  15. An improved lower bound for the time complexity of mutual exclusion Distributed Computing · Springer Science+Business Media · 2002 10.1007/s00446-002-0084-2
  16. Mutual Exclusion Algorithms with Constant RMR Complexity and Wait-Free Exit Code. International Conference on Principles of Distributed Systems · 2017
  17. Lock–Unlock ACM Transactions on Computer Systems · Association for Computing Machinery · 2018 10.1145/3301501
  18. LockDoc 2019 10.1145/3302424.3303948
  19. Performance Prediction for Coarse-Grained Locking arXiv (Cornell University) · Cornell University · 2019 10.48550/arxiv.1904.11323
  20. Compact NUMA-aware Locks 2019 10.1145/3302424.3303984
  21. A Relational Theory of Locality ACM Transactions on Architecture and Code Optimization · Association for Computing Machinery · 2019 10.1145/3341109
  22. Towards an Ideal Queue Lock 2020 10.1145/3369740.3369784
  23. Fissile Locks Lecture notes in computer science · Springer Science+Business Media · 2021 10.1007/978-3-030-67087-0_13
  24. Be my guest ACM SIGPLAN Notices · Association for Computing Machinery · 2016 10.1145/3016078.2851160
  25. Euro-Par 2019: Parallel Processing Lecture notes in computer science · Springer Science+Business Media · 2019 10.1007/978-3-030-29400-7
  26. Hemlock 2021 10.1145/3409964.3461805
  27. Peformance Prediction for Coarse-Grained Locking: MCS Case. arXiv (Cornell University) · Cornell University · 2021
  28. An efficient meta-lock for implementing ubiquitous synchronization ACM SIGPLAN Notices · Association for Computing Machinery · 1999 10.1145/320385.320402
  29. MCSH, a Lock with the Standard Interface ACM Transactions on Parallel Computing · Association for Computing Machinery · 2023 10.1145/3584696
  30. Shared-Memory Synchronization Synthesis lectures on computer architecture · Morgan & Claypool Publishers · 2024 10.1007/978-3-031-38684-8