Skip to content

Instantly share code, notes, and snippets.

@nem0
Created October 8, 2024 22:42
Show Gist options
  • Save nem0/21216dafca5883579a4042230e1a3032 to your computer and use it in GitHub Desktop.
Save nem0/21216dafca5883579a4042230e1a3032 to your computer and use it in GitHub Desktop.
bool pop(T& obj) {
for (;;) {
const i32 pos = rd;
Item* j = &objects[pos % CAPACITY];
const i32 seq = j->seq;
if (seq < pos + 1) {
// nothing to pop
return false;
}
else if (seq == pos + 1) {
// try to pop
if (rd.compareExchange(pos + 1, pos)) {
obj = j->value;
memoryBarrier();
j->seq = pos + CAPACITY;
return true;
}
// somebody popped before us, try again
}
else {
// somebody popped before we got here, try again
ASSERT(rd != pos);
}
}
}
void push(const T& obj, Lumix::Mutex* mutex) {
for (;;) {
const i32 pos = wr;
Item* j = &objects[pos % CAPACITY];
const i32 seq = j->seq;
if (seq < pos) {
// buffer full
if (mutex) mutex->enter();
m_fallback.push(obj);
if (mutex) mutex->exit();
return;
}
else if (seq == pos) {
// we can try to push
if (wr.compareExchange(pos + 1, pos)) {
j->value = obj;
memoryBarrier();
j->seq = pos + 1;
break;
}
}
else {
// somebody pushed before us, try again
ASSERT(wr != pos);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment