Cats STM

Cats STM

  • Docs
  • API
  • GitHub

›Data Types

Overview

  • Getting started

Theory

  • Introduction
  • Txn
  • TVar

Data Types

  • TMVar
  • TQueue
  • TSemaphore

Worked Examples

  • The Santa Claus Problem

TMVar

A convenience implementation built on top of TVar, which provides similar semantics to Cats Effect MVar.

You can think of this as a mutable memory location that may contain a value. Writes will block if full and reads will block if empty.

import cats.effect.IO
import cats.effect.unsafe.implicits.global
import cats.syntax.semigroup._
import cats.instances.string._

import io.github.timwspence.cats.stm.STM

val stm = STM.runtime[IO].unsafeRunSync()
// stm: STM[IO] = io.github.timwspence.cats.stm.STM$Make$$anon$1$$anon$2@1c24f14b
import stm._

val txn: Txn[String] = for {
  tmvar     <- TMVar.empty[String]
  _         <- tmvar.put("Hello")   //Would block if full
  hello     <- tmvar.take           //Would block if empty
  _         <- tmvar.put("world")   //Would block if full
  world     <- tmvar.read           //Would block if empty.
} yield hello |+| world
// txn: Txn[String] = Bind(
//   txn = Bind(
//     txn = Alloc(
//       v = Delay(
//         thunk = cats.effect.IO$$$Lambda$9603/0x0000000802cb0440@84b0ba4,
//         event = cats.effect.tracing.TracingEvent$StackTrace
//       )
//     ),
//     f = scala.Function1$$Lambda$9648/0x0000000802d45040@5b3d8344
//   ),
//   f = <function1>
// )

val result = stm.commit(txn).unsafeRunSync()
// result: String = "Helloworld"
← TVarTQueue →
Docs
Getting startedExamples
Community
BlogGitter
More
Star
Follow @TimWSpence
Copyright © 2018-2022 Tim Spence