Software transactional memory with TL2

This project originally started as part of the Concurrent Computing course taught by Rachid Guerraoui at EPFL.

Transactional memory lets threads share memory and access it inside transactions. A transaction either commits all its writes at once, or aborts and leaves memory unchanged. In this project I implemented Transactional Locking II (TL2), a software transactional memory (STM), in C++17.

The code is on GitHub: https://github.com/chutommy/transactional-memory-tl2

Motivation

A bank keeps the balance of every account in shared memory. A transfer reads the balance of the source, checks that it is sufficient, and writes the two new balances. An audit sums all the balances.

Without synchronization, the steps of two threads interleave. Below, every account holds 100, and each step of a transaction reads or writes shared memory directly.

A single global lock around every transaction prevents both, but then only one transaction runs at a time, even if 2 transfers use different accounts. With transactional memory, transactions run concurrently and still behave as if they ran one at a time.

Interface

A region is a set of shared memory segments. Memory is read and written in words of a fixed size. The addresses of a region are not regular pointers. They can only be passed to tm_read, tm_write and tm_free.

tm_begin → tm_read tm_write tm_alloc tm_free → tm_end → committed

Transactional memory

Region

tm_create(size, align)shared_t

Creates a region with one zero-initialized segment of size bytes. align is the word size in bytes.

tm_start(tm)void *

Returns the address of the first segment. tm_size and tm_align return its size and the word size.

tm_destroy(tm)void

Destroys the region. No transaction may be running on it.

Transaction

tm_begin(tm, is_ro)tx_t

Begins a transaction. is_ro marks it as read-only. A thread can run one transaction at a time.

tm_read(tm, tx, source, size, target)bool

Copies size bytes from shared memory at source to the private buffer target.

tm_write(tm, tx, source, size, target)bool

Copies size bytes from the private buffer source to shared memory at target.

tm_alloc(tm, tx, size, &target)Alloc

Allocates a zero-initialized segment of size bytes and stores its address in target.

tm_free(tm, tx, target)bool

Frees a segment allocated with tm_alloc. It is freed when the transaction commits.

tm_end(tm, tx)bool

Tries to commit the transaction. Returns true if it committed.

Properties

1
Atomicity

If a transaction commits, all of its writes are applied together. If it aborts, none of them are.

2
Opacity

Committed transactions behave as if they ran one after another. A transaction never reads an inconsistent state, even if it later aborts.

The bank example

shared_t tm = tm_create(4 * 8, 8); // 4 accounts of 8 bytes
void *accounts = tm_start(tm);     // address of the first account
// ...
tm_destroy(tm);
// moves 'amount' from 'from' to 'to', false on insufficient funds
bool transfer(shared_t tm, void *from, void *to, int64_t amount) {
  while (true) { // retry until it commits
    tx_t tx = tm_begin(tm, false);
    int64_t a, b;
    if (!tm_read(tm, tx, from, 8, &a))
      continue; // aborted
    if (a < amount) {
      if (tm_end(tm, tx))
        return false;
      continue;
    }
    if (!tm_read(tm, tx, to, 8, &b))
      continue;
    a -= amount;
    b += amount;
    if (!tm_write(tm, tx, &a, 8, from))
      continue;
    if (!tm_write(tm, tx, &b, 8, to))
      continue;
    if (tm_end(tm, tx))
      return true;
  }
}
// returns the sum of 'count' balances starting at 'accounts'
int64_t audit(shared_t tm, void *accounts, size_t count) {
  std::vector<int64_t> balances(count);
  while (true) {
    tx_t tx = tm_begin(tm, true); // read-only
    if (!tm_read(tm, tx, accounts, 8 * count, balances.data()))
      continue;
    if (tm_end(tm, tx))
      return std::accumulate(balances.begin(), balances.end(),
                             int64_t(0));
  }
}

TL2

TL2 keeps a version and a lock for every word, and one global version clock for the region.

The same examples with TL2:

During steps 1 to 5 of a commit, the words of the write set are locked. A transaction that reads one of them aborts.

A read-only transaction does not keep a read set. Each of its reads was already checked against rv, so tm_end commits immediately. Same applies for transactions that didn’t write anything.

Versioned lock

The version and the lock of a word are stored together in one 32-bit atomic: 31 bits for the version and 1 bit for the lock.

tm_read loads the atomic once to get both the lock bit and the version. After copying the word it loads the atomic again, and aborts if the value changed during the copy:

uint32_t snap = source_lock->vl.load(std::memory_order_acquire);
if (unlikely(VL::is_locked(snap) || VL::version_of(snap) > tx.read_version))
  return false;
std::memcpy(to, from, region.align);
std::atomic_thread_fence(std::memory_order_acquire);
return likely(snap == source_lock->vl.load(std::memory_order_relaxed));

Every word has its own lock, so a region of 8-byte words uses 4 extra bytes per word. The locks are not padded to cache lines. Padding would prevent false sharing between neighbouring locks, but each lock would then take 64 bytes.

Addresses

The addresses returned to the user are not real pointers. The upper 16 bits of an address hold the segment index and the lower 48 bits hold the offset in the segment. The index is stored incremented by 1, so a valid address is never null. A region can have up to 65535 segments.

A segment is one allocation. It starts with the locks (4 bytes per word, padded to the word size), followed by the data. Below are 3 segments of 8, 5 and 3 words. Selecting a word shows its address and the location of its lock and data.

Write set

A transaction must see its own writes, so tm_read first checks whether the word is in the write set. The write set is a vector, and searching it is linear. To skip the search in most cases, the transaction keeps a 4096-bit Bloom filter of the written addresses. The write set is searched only if the filter reports that the address may be in it.

The validation of the read set at commit is skipped if wv == rv + 1. In that case no other transaction committed since this one began.

uint32_t write_version = region->global_version.fetch_add(1) + 1;
// no writes can happen between reads and writes (we hold locks)
if (tx->read_version + 1 != write_version) {

Memory reclamation

tm_alloc and tm_free add and remove segments inside a transaction.

Each thread stores the read version of its running transaction where other threads can read it. A retired segment is deleted when every running transaction has a read version greater than or equal to the clock value saved with the segment. Its index can then be reused.

uint32_t oldest = TX::oldest(this);
auto kept = retired.begin();
for (const Retired &r : retired) {
  if (r.version <= oldest) {
    delete segments[r.segment];
    segments[r.segment] = nullptr;
  } else {
    *kept++ = r;
  }
}
retired.erase(kept, retired.end());

References

  1. D. Dice, O. Shalev, N. Shavit. Transactional Locking II. DISC 2006.
    https://doi.org/10.1007/11864219_14
  2. R. Guerraoui, M. Kapałka. Principles of Transactional Memory. 2010.
    https://doi.org/10.1007/978-3-031-02002-5