in ktor-utils/posix/src/io/ktor/util/collections/LockFreeMPSCQueueNative.kt [146:168]
public fun removeFirstOrNull(): Any? {
_state.loop { state ->
if (state and FROZEN_MASK != 0L) return REMOVE_FROZEN // frozen -- cannot modify
state.withState { head, tail ->
if ((tail and mask) == (head and mask)) return null // empty
// because queue is Single Consumer, then element == null|Placeholder can only be when add has not finished yet
val element = array[head and mask].value ?: return null
if (element is Placeholder) return null // same story -- consider it not added yet
// we cannot put null into array here, because copying thread could replace it with Placeholder and that is a disaster
val newHead = (head + 1) and MAX_CAPACITY_MASK
if (_state.compareAndSet(state, state.updateHead(newHead))) {
array[head and mask].value = null // now can safely put null (state was updated)
return element // successfully removed in fast-path
}
// Slow-path for remove in case of interference
var cur = this
while (true) {
@Suppress("UNUSED_VALUE")
cur = cur.removeSlowPath(head, newHead) ?: return element
}
}
}
}