diff options
author | Chris Wendt <chrismwendt@gmail.com> | 2022-06-08 02:28:37 -0600 |
---|---|---|
committer | Chris Wendt <chrismwendt@gmail.com> | 2022-06-08 03:02:44 -0600 |
commit | 30943ded71e123886291ad393e55bfb6aa837df3 (patch) | |
tree | ca7cc2520959386d6c57d9204f284be217bb0b72 /doc.go | |
parent | use generic atomic (diff) | |
download | stm-30943ded71e123886291ad393e55bfb6aa837df3.tar.gz stm-30943ded71e123886291ad393e55bfb6aa837df3.tar.xz |
BIG change: generic Var[T], txVar, etc.
Diffstat (limited to 'doc.go')
-rw-r--r-- | doc.go | 16 |
1 files changed, 8 insertions, 8 deletions
@@ -10,14 +10,14 @@ it non-atomic). To begin, create an STM object that wraps the data you want to access concurrently. - x := stm.NewVar(3) + x := stm.NewVar[int](3) You can then use the Atomically method to atomically read and/or write the the data. This code atomically decrements x: stm.Atomically(func(tx *stm.Tx) { - cur := tx.Get(x).(int) - tx.Set(x, cur-1) + cur := x.Get(tx) + x.Set(tx, cur-1) }) An important part of STM transactions is retrying. At any point during the @@ -29,11 +29,11 @@ updated before the transaction will be rerun. As an example, this code will try to decrement x, but will block as long as x is zero: stm.Atomically(func(tx *stm.Tx) { - cur := tx.Get(x).(int) + cur := x.Get(tx) if cur == 0 { tx.Retry() } - tx.Set(x, cur-1) + x.Set(tx, cur-1) }) Internally, tx.Retry simply calls panic(stm.Retry). Panicking with any other @@ -47,13 +47,13 @@ retried. For example, this code implements the "decrement-if-nonzero" transaction above, but for two values. It will first try to decrement x, then y, and block if both values are zero. - func dec(v *stm.Var) { + func dec(v *stm.Var[int]) { return func(tx *stm.Tx) { - cur := tx.Get(v).(int) + cur := v.Get(tx) if cur == 0 { tx.Retry() } - tx.Set(v, cur-1) + v.Set(tx, cur-1) } } |