HORIZON HASKELLDocslts/ghc-9.10.xc74966e2026-09-27Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · c74966e · 2026-09-27

Moduleatomic-primops-0.8.8Haskell2010

Data.Atomics.Counter

Integer counters providing thread-safe, lock-free mutation functions.

Atomic counters are represented by a single memory location, such that built-in processor instructions are sufficient to perform fetch-and-add or compare-and-swap.

Remember, contention on such counters should still be minimized!

  • 2 types
  • 8 values

Type of counters of counters and tickets

1 declaration

Creating counters

1 declaration

Tickets, used for compare-and-swap

2 declarations

See the documentation for Data.Atomics for more explanation of the ticket abstraction. The same ideas apply here for counters as for general mutable locations (IORefs).

typetype CTicket = Int
#

You should not depend on this type. It varies between different implementations of atomic counters.

valuepeekCTicket :: CTicket -> Int
#

Opaque tickets cannot be constructed, but they can be destructed into values.

Atomic memory operations

3 declarations

Compare and swap for the counter ADT. Similar behavior to casIORef, in particular, in both success and failure cases it returns a ticket that you should use for the next attempt. (That is, in the success case, it actually returns the new value that you provided as input, but in ticket form.)

valueincrCounter :: Int -> AtomicCounter -> IO Int
#

Increment the counter by a given amount. Returns the value AFTER the increment (in contrast with the behavior of the underlying instruction on architectures like x86.)

Note that UNLIKE with boxed implementations of counters, where increment is based on CAS, this increment is O(1). Fetch-and-add does not require a retry loop like CAS.

Non-atomic operations

3 declarations