Skip to content

Instantly share code, notes, and snippets.

@pervognsen
Last active December 18, 2022 08:11
Show Gist options
  • Save pervognsen/fe56a001c3dbf238ae23e73ebf5e6765 to your computer and use it in GitHub Desktop.
Save pervognsen/fe56a001c3dbf238ae23e73ebf5e6765 to your computer and use it in GitHub Desktop.
// assume sequential consistency.
// this technique prevents frequent synchronization (cache line thrashing) of the read/write positions
// in the case where the ring buffer is running neither too close to full or too close to empty. it
// relies on the fact that an out of date notion of the read/write positions are conservative approximations.
// globals in shared memory. assume in different cache lines to prevent false sharing.
int read_pos, write_pos;
// reader
int last_write_pos = write_pos; // synchronize
for (;;) {
while (read_pos == last_write_pos) {
last_write_pos = write_pos; // synchronize
if (read_pos == last_write_pos)
wait();
}
read_next();
read_pos = (read_pos + 1) & MASK;
}
// writer
int last_read_pos = read_pos; // synchronize
for (;;) {
while (write_pos + 1 == last_read_pos) {
last_read_pos = read_pos; // synchronize
if (write_pos + 1 == last_read_pos)
wait();
}
write_next();
write_pos = (write_pos + 1) & MASK;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment