Last active
December 18, 2022 08:11
-
-
Save pervognsen/fe56a001c3dbf238ae23e73ebf5e6765 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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