github.com/puzpuzpuz/xsync/v3@v3.1.1-0.20240225193106-cbe4ec1e954f/README.md (about)

     1  [![GoDoc reference](https://img.shields.io/badge/godoc-reference-blue.svg)](https://pkg.go.dev/github.com/puzpuzpuz/xsync/v3)
     2  [![GoReport](https://goreportcard.com/badge/github.com/puzpuzpuz/xsync/v3)](https://goreportcard.com/report/github.com/puzpuzpuz/xsync/v3)
     3  [![codecov](https://codecov.io/gh/puzpuzpuz/xsync/branch/main/graph/badge.svg)](https://codecov.io/gh/puzpuzpuz/xsync)
     4  
     5  # xsync
     6  
     7  Concurrent data structures for Go. Aims to provide more scalable alternatives for some of the data structures from the standard `sync` package, but not only.
     8  
     9  Covered with tests following the approach described [here](https://puzpuzpuz.dev/testing-concurrent-code-for-fun-and-profit).
    10  
    11  ## Benchmarks
    12  
    13  Benchmark results may be found [here](BENCHMARKS.md). I'd like to thank [@felixge](https://github.com/felixge) who kindly ran the benchmarks on a beefy multicore machine.
    14  
    15  Also, a non-scientific, unfair benchmark comparing Java's [j.u.c.ConcurrentHashMap](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/ConcurrentHashMap.html) and `xsync.MapOf` is available [here](https://puzpuzpuz.dev/concurrent-map-in-go-vs-java-yet-another-meaningless-benchmark).
    16  
    17  ## Usage
    18  
    19  The latest xsync major version is v3, so `/v3` suffix should be used when importing the library:
    20  
    21  ```go
    22  import (
    23  	"github.com/puzpuzpuz/xsync/v3"
    24  )
    25  ```
    26  
    27  *Note for v1 and v2 users*: v1 and v2 support is discontinued, so please upgrade to v3. While the API has some breaking changes, the migration should be trivial.
    28  
    29  ### Counter
    30  
    31  A `Counter` is a striped `int64` counter inspired by the `j.u.c.a.LongAdder` class from the Java standard library.
    32  
    33  ```go
    34  c := xsync.NewCounter()
    35  // increment and decrement the counter
    36  c.Inc()
    37  c.Dec()
    38  // read the current value
    39  v := c.Value()
    40  ```
    41  
    42  Works better in comparison with a single atomically updated `int64` counter in high contention scenarios.
    43  
    44  ### Map
    45  
    46  A `Map` is like a concurrent hash table-based map. It follows the interface of `sync.Map` with a number of valuable extensions like `Compute` or `Size`.
    47  
    48  ```go
    49  m := xsync.NewMap()
    50  m.Store("foo", "bar")
    51  v, ok := m.Load("foo")
    52  s := m.Size()
    53  ```
    54  
    55  `Map` uses a modified version of Cache-Line Hash Table (CLHT) data structure: https://github.com/LPD-EPFL/CLHT
    56  
    57  CLHT is built around the idea of organizing the hash table in cache-line-sized buckets, so that on all modern CPUs update operations complete with minimal cache-line transfer. Also, `Get` operations are obstruction-free and involve no writes to shared memory, hence no mutexes or any other sort of locks. Due to this design, in all considered scenarios `Map` outperforms `sync.Map`.
    58  
    59  One important difference with `sync.Map` is that only string keys are supported. That's because Golang standard library does not expose the built-in hash functions for `interface{}` values.
    60  
    61  `MapOf[K, V]` is an implementation with parametrized key and value types. While it's still a CLHT-inspired hash map, `MapOf`'s design is quite different from `Map`. As a result, less GC pressure and fewer atomic operations on reads.
    62  
    63  ```go
    64  m := xsync.NewMapOf[string, string]()
    65  m.Store("foo", "bar")
    66  v, ok := m.Load("foo")
    67  ```
    68  
    69  One important difference with `Map` is that `MapOf` supports arbitrary `comparable` key types:
    70  
    71  ```go
    72  type Point struct {
    73  	x int32
    74  	y int32
    75  }
    76  m := NewMapOf[Point, int]()
    77  m.Store(Point{42, 42}, 42)
    78  v, ok := m.Load(point{42, 42})
    79  ```
    80  
    81  ### MPMCQueue
    82  
    83  A `MPMCQueue` is a bounded multi-producer multi-consumer concurrent queue.
    84  
    85  ```go
    86  q := xsync.NewMPMCQueue(1024)
    87  // producer inserts an item into the queue
    88  q.Enqueue("foo")
    89  // optimistic insertion attempt; doesn't block
    90  inserted := q.TryEnqueue("bar")
    91  // consumer obtains an item from the queue
    92  item := q.Dequeue() // interface{} pointing to a string
    93  // optimistic obtain attempt; doesn't block
    94  item, ok := q.TryDequeue()
    95  ```
    96  
    97  `MPMCQueueOf[I]` is an implementation with parametrized item type. It is available for Go 1.19 or later.
    98  
    99  ```go
   100  q := xsync.NewMPMCQueueOf[string](1024)
   101  q.Enqueue("foo")
   102  item := q.Dequeue() // string
   103  ```
   104  
   105  The queue is based on the algorithm from the [MPMCQueue](https://github.com/rigtorp/MPMCQueue) C++ library which in its turn references D.Vyukov's [MPMC queue](https://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue). According to the following [classification](https://www.1024cores.net/home/lock-free-algorithms/queues), the queue is array-based, fails on overflow, provides causal FIFO, has blocking producers and consumers.
   106  
   107  The idea of the algorithm is to allow parallelism for concurrent producers and consumers by introducing the notion of tickets, i.e. values of two counters, one per producers/consumers. An atomic increment of one of those counters is the only noticeable contention point in queue operations. The rest of the operation avoids contention on writes thanks to the turn-based read/write access for each of the queue items.
   108  
   109  In essence, `MPMCQueue` is a specialized queue for scenarios where there are multiple concurrent producers and consumers of a single queue running on a large multicore machine.
   110  
   111  To get the optimal performance, you may want to set the queue size to be large enough, say, an order of magnitude greater than the number of producers/consumers, to allow producers and consumers to progress with their queue operations in parallel most of the time.
   112  
   113  ### RBMutex
   114  
   115  A `RBMutex` is a reader-biased reader/writer mutual exclusion lock. The lock can be held by many readers or a single writer.
   116  
   117  ```go
   118  mu := xsync.NewRBMutex()
   119  // reader lock calls return a token
   120  t := mu.RLock()
   121  // the token must be later used to unlock the mutex
   122  mu.RUnlock(t)
   123  // writer locks are the same as in sync.RWMutex
   124  mu.Lock()
   125  mu.Unlock()
   126  ```
   127  
   128  `RBMutex` is based on a modified version of BRAVO (Biased Locking for Reader-Writer Locks) algorithm: https://arxiv.org/pdf/1810.01553.pdf
   129  
   130  The idea of the algorithm is to build on top of an existing reader-writer mutex and introduce a fast path for readers. On the fast path, reader lock attempts are sharded over an internal array based on the reader identity (a token in the case of Golang). This means that readers do not contend over a single atomic counter like it's done in, say, `sync.RWMutex` allowing for better scalability in terms of cores.
   131  
   132  Hence, by the design `RBMutex` is a specialized mutex for scenarios, such as caches, where the vast majority of locks are acquired by readers and write lock acquire attempts are infrequent. In such scenarios, `RBMutex` should perform better than the `sync.RWMutex` on large multicore machines.
   133  
   134  `RBMutex` extends `sync.RWMutex` internally and uses it as the "reader bias disabled" fallback, so the same semantics apply. The only noticeable difference is in the reader tokens returned from the `RLock`/`RUnlock` methods.
   135  
   136  ## License
   137  
   138  Licensed under MIT.