Created
October 8, 2024 22:42
-
-
Save nem0/21216dafca5883579a4042230e1a3032 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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