Published Cell

easy · memory, atomic, happens-before, synchronization

Published Cell

In this lab, build a small lock-free publication primitive using atomic.Pointer.

Function signatures

type PublishedCell struct { ... }

func NewPublishedCell() *PublishedCell
func (c *PublishedCell) Store(value int)
func (c *PublishedCell) Load() (value int, ok bool)
func (c *PublishedCell) Swap(value int) (previous int, ok bool)

Contract

  • Store publishes a new immutable snapshot.
  • Load returns (0, false) when no value has been published yet.
  • Swap returns the previous published value and true when one exists; returns (0, false) if empty.
  • The API must be safe for concurrent readers and writers.
  • Readers must never observe a partially initialized state.
  • Avoid additional synchronization where atomics are sufficient.

Notes

  • Use sync/atomic pointer APIs.
  • Keep behavior deterministic for nil receiver calls.
  • Do not panic on empty cells.

Complexity

  • Store, Load, Swap: O(1).
Run tests to see results
No issues detected
    Join Discord