#[allow(unused_variables)]
fn mpsc_options_default_inner() -> MpscQueueOptions {
MpscQueueOptions {
cleanup_batch_size: const { NonZeroUsize::new(64).unwrap() },
push_attempts: const { NonZeroU8::new(3).unwrap() },
}
}
#[allow(unused_variables)]
fn mpsc_queue_new_inner(options: MpscQueueOptions) -> pi_result::Result<MpscTaskQueue> {
let stub = MpscEntryHandle::try_new_empty()?;
let endpoint = MpscEntryHandle::try_new_empty()?;
Ok(MpscTaskQueue {
shared: Arc::new(MpscQueueShared {
queue: cordyceps::MpscQueue::new_with_stub(stub),
state: AtomicUsize::new(0),
clear: UnsafeCell::new(MpscClearState::Available(endpoint)),
options,
}),
})
}
#[allow(unused_variables)]
fn mpsc_queue_handle_inner(this: &MpscTaskQueue) -> MpscTaskQueueHandle {
MpscTaskQueueHandle { shared: Arc::clone(&this.shared) }
}
#[allow(unused_variables)]
fn mpsc_queue_clear_inner(this: &mut MpscTaskQueue) -> pi_result::Result<QueueCleanupProgress> {
match this.shared.cleanup_step(MpscCleanupMode::Clear) {
MpscCleanupStep::Complete => Ok(QueueCleanupProgress::Complete),
MpscCleanupStep::MoreWork | MpscCleanupStep::Deferred => Ok(QueueCleanupProgress::MoreWork),
MpscCleanupStep::Busy => Err(pi_result::Error::new(pi_result::ErrorKind::Busy)
.attach("MPSC清理(clear)未取得唯一消费者(Consumer),已有持有者占用")),
}
}
#[allow(unused_variables)]
fn mpsc_queue_close_inner(this: &mut MpscTaskQueue) -> pi_result::Result<QueueCleanupProgress> {
this.shared.stop_accepting();
match this.shared.cleanup_step(MpscCleanupMode::Close) {
MpscCleanupStep::Complete => Ok(QueueCleanupProgress::Complete),
MpscCleanupStep::MoreWork | MpscCleanupStep::Deferred => Ok(QueueCleanupProgress::MoreWork),
MpscCleanupStep::Busy => Err(pi_result::Error::new(pi_result::ErrorKind::Busy)
.attach("MPSC关闭(close)已永久停收,但未取得唯一消费者(Consumer),已有持有者占用")),
}
}
#[allow(unused_variables)]
fn mpsc_handle_clone_inner(this: &MpscTaskQueueHandle) -> MpscTaskQueueHandle {
MpscTaskQueueHandle { shared: Arc::clone(&this.shared) }
}
#[allow(unused_variables)]
fn mpsc_take_one_inner(
this: &MpscTaskQueueHandle,
completion: &mut MpscCompletionGuard<'_>,
) -> MpscTake {
let mut result = MpscTake::Empty;
let Some(mut consumer) = MpscConsumerGuard::try_new(&this.shared) else { return MpscTake::Busy; };
completion.arm();
loop {
match consumer.try_take() {
Ok(Some(task)) => {
result = MpscTake::Ready(task);
consumer.handed_off += 1;
break;
}
Ok(None) => continue,
Err(TryDequeueError::Empty) => {
if this.shared.state.load(std::sync::atomic::Ordering::Relaxed) & COUNT_MASK != 0 {
result = MpscTake::WouldBlock;
}
break;
}
Err(TryDequeueError::Inconsistent) => {
result = MpscTake::WouldBlock;
break;
}
Err(TryDequeueError::Busy) => std::process::abort(),
}
}
drop(consumer);
result
}
#[allow(unused_variables)]
fn mpsc_is_empty_inner(this: &MpscTaskQueueHandle) -> bool {
this.shared.state.load(std::sync::atomic::Ordering::Relaxed) & COUNT_MASK == 0
}
#[allow(unused_variables)]
fn mpsc_push_inner(
this: &MpscTaskQueueHandle,
task: Runnable,
completion: &mut MpscCompletionGuard<'_>,
) -> pi_result::RawResult<(), ExternalPushError> {
let entry = match MpscEntryHandle::try_from_runnable(task) {
Ok(entry) => entry,
Err(task) => return Err(ExternalPushError { task, cause: ExternalPushErrorKind::LinkMissing }),
};
if let Err(cause) = this.shared.try_reserve() {
let task = entry.try_into_runnable().unwrap_or_else(|_| std::process::abort());
return Err(ExternalPushError { task, cause });
}
this.shared.queue.enqueue(entry);
completion.arm();
Ok(())
}
#[allow(unused_variables)]
fn mpsc_take_batch_inner(
this: &MpscTaskQueueHandle,
count: usize,
completion: &mut MpscCompletionGuard<'_>,
) -> BatchAttempt {
let mut batch = crate::external::TaskBatch::from_tasks(VecDeque::with_capacity(count));
let Some(mut consumer) = MpscConsumerGuard::try_new(&this.shared) else { return BatchAttempt::Busy; };
completion.arm();
let mut blocked = false;
while consumer.handed_off < count {
match consumer.try_take() {
Ok(Some(task)) => {
batch.tasks.push_back(task);
consumer.handed_off += 1;
}
Ok(None) => continue,
Err(TryDequeueError::Empty) => {
blocked = this.shared.state.load(std::sync::atomic::Ordering::Relaxed) & COUNT_MASK != 0;
break;
}
Err(TryDequeueError::Inconsistent) => {
blocked = true;
break;
}
Err(TryDequeueError::Busy) => std::process::abort(),
}
}
drop(consumer);
if !batch.tasks.is_empty() {
BatchAttempt::Ready(batch)
} else if blocked {
BatchAttempt::WouldBlock
} else {
BatchAttempt::Empty
}
}
#[allow(unused_variables)]
fn mpsc_len_inner(this: &MpscTaskQueueHandle) -> usize {
this.shared.state.load(std::sync::atomic::Ordering::Relaxed) & COUNT_MASK
}
#[allow(unused_variables)]
fn mpsc_reserve_inner(this: &MpscQueueShared) -> pi_result::RawResult<(), ExternalPushErrorKind> {
use std::sync::atomic::Ordering::Relaxed;
let mut state = this.state.load(Relaxed);
for _ in 0..this.options.push_attempts.get() {
if state & STOP_ACCEPTING != 0 {
return Err(ExternalPushErrorKind::Closed);
}
if state & COUNT_MASK == COUNT_MASK {
return Err(ExternalPushErrorKind::CountOverflow);
}
match this.state.compare_exchange(state, state + 1, Relaxed, Relaxed) {
Ok(_) => return Ok(()),
Err(actual) => state = actual,
}
}
Err(ExternalPushErrorKind::Busy)
}
#[allow(unused_variables)]
fn mpsc_start_take_inner(this: &MpscQueueShared) -> Option<usize> {
let state = this.state.fetch_or(0, std::sync::atomic::Ordering::Acquire);
if state & STOP_ACCEPTING != 0 { None } else { Some(state & COUNT_MASK) }
}
#[allow(unused_variables)]
fn mpsc_return_count_inner(this: &MpscQueueShared, count: usize) {
if count != 0 {
this.state.fetch_sub(count, std::sync::atomic::Ordering::Release);
}
}
#[allow(unused_variables)]
fn mpsc_stop_accepting_inner(this: &MpscQueueShared) {
this.state.fetch_or(STOP_ACCEPTING, std::sync::atomic::Ordering::AcqRel);
}
#[allow(unused_variables)]
fn mpsc_manager_released_inner(this: &MpscQueueShared) {
this.state.fetch_or(
STOP_ACCEPTING | MANAGER_RELEASED | CLEANUP_REQUESTED,
std::sync::atomic::Ordering::AcqRel,
);
}
#[allow(unused_variables)]
fn mpsc_confirm_exit_inner(this: &MpscQueueShared) -> bool {
this.state.fetch_or(0, std::sync::atomic::Ordering::AcqRel) & MANAGER_RELEASED != 0
}
#[allow(unused_variables)]
fn mpsc_request_cleanup_inner(this: &MpscQueueShared) {
this.state.fetch_or(CLEANUP_REQUESTED, std::sync::atomic::Ordering::AcqRel);
}
#[allow(unused_variables)]
fn mpsc_cleanup_step_inner(
this: &MpscQueueShared,
mode: MpscCleanupMode,
completion: Option<&mut MpscCompletionGuard<'_>>,
) -> MpscCleanupStep {
use std::sync::atomic::Ordering::AcqRel;
let owner_exit = matches!(mode, MpscCleanupMode::OwnerExit);
let mut cleanup = MpscCleanupGuard::new(this, owner_exit);
let budget = this.options.cleanup_batch_size.get();
cleanup.prepare(budget);
let Some(mut consumer) = MpscConsumerGuard::try_new(this) else {
cleanup.disarm();
return MpscCleanupStep::Busy;
};
if let Some(completion) = completion { completion.arm(); }
let state = this.state.fetch_and(!CLEANUP_REQUESTED, AcqRel);
let closing = !matches!(mode, MpscCleanupMode::Clear) || state & STOP_ACCEPTING != 0;
let mut endpoint_progress = false;
if !closing {
if consumer.acknowledge_clear() {
drop(consumer);
cleanup.disarm();
return MpscCleanupStep::Complete;
}
consumer.begin_clear();
} else if state & COUNT_MASK == 0 {
endpoint_progress |= consumer.acknowledge_clear();
}
let mut result = MpscCleanupStep::MoreWork;
for _ in 0..budget {
if !closing {
if unsafe { matches!(&*this.clear.get(), MpscClearState::Reached(_)) } {
if cleanup.pending.is_empty() {
endpoint_progress |= consumer.acknowledge_clear();
result = MpscCleanupStep::Complete;
}
break;
}
}
match consumer.try_take() {
Ok(Some(task)) => cleanup.pending.push_back(task),
Ok(None) => {
endpoint_progress = true;
if !closing {
if cleanup.pending.is_empty() {
endpoint_progress |= consumer.acknowledge_clear();
result = MpscCleanupStep::Complete;
}
break;
}
if cleanup.pending.is_empty() && this.state.fetch_or(0, AcqRel) & COUNT_MASK == 0 {
endpoint_progress |= consumer.acknowledge_clear();
}
}
Err(TryDequeueError::Empty) => {
let available = unsafe { matches!(&*this.clear.get(), MpscClearState::Available(_)) };
result = if closing && available && this.state.fetch_or(0, AcqRel) & COUNT_MASK == 0 {
MpscCleanupStep::Complete
} else {
MpscCleanupStep::Deferred
};
break;
}
Err(TryDequeueError::Inconsistent) => {
result = MpscCleanupStep::Deferred;
break;
}
Err(TryDequeueError::Busy) => std::process::abort(),
}
}
let processed = !cleanup.pending.is_empty();
drop(consumer);
cleanup.drain();
let progressed = processed || endpoint_progress;
if owner_exit && progressed { mpsc_request_cleanup_inner(this); }
let state = this.state.fetch_or(0, AcqRel);
if closing && !matches!(result, MpscCleanupStep::Complete)
&& (progressed || state & CLEANUP_REQUESTED != 0) {
result = MpscCleanupStep::MoreWork;
}
cleanup.disarm();
result
}
#[allow(unused_variables)]
fn mpsc_consumer_new_inner(shared: &MpscQueueShared) -> Option<MpscConsumerGuard<'_>> {
shared.queue.try_consume().map(|consumer| MpscConsumerGuard {
shared,
consumer: Some(consumer),
handed_off: 0,
endpoint: None,
})
}
#[allow(unused_variables)]
fn mpsc_consumer_take_inner(
this: &mut MpscConsumerGuard<'_>,
) -> pi_result::RawResult<Option<Runnable>, TryDequeueError> {
let entry = this.consumer.as_ref().unwrap_or_else(|| std::process::abort()).try_dequeue()?;
match entry.try_into_runnable() {
Ok(task) => Ok(Some(task)),
Err(endpoint) => {
unsafe {
let clear = this.shared.clear.get();
if !matches!(&*clear, MpscClearState::Queued) { std::process::abort(); }
clear.write(MpscClearState::Reached(endpoint));
}
Ok(None)
}
}
}
#[allow(unused_variables)]
fn mpsc_consumer_begin_clear_inner(this: &mut MpscConsumerGuard<'_>) {
if this.shared.state.load(std::sync::atomic::Ordering::Acquire) & STOP_ACCEPTING != 0 {
return;
}
unsafe {
let clear = this.shared.clear.get();
if !matches!(&*clear, MpscClearState::Available(_)) { return; }
let MpscClearState::Available(endpoint) = clear.replace(MpscClearState::Transferring) else {
std::process::abort();
};
this.endpoint = Some(endpoint);
}
this.shared.queue.enqueue(this.endpoint.take().unwrap_or_else(|| std::process::abort()));
unsafe { this.shared.clear.get().write(MpscClearState::Queued); }
}
#[allow(unused_variables)]
fn mpsc_consumer_acknowledge_inner(this: &mut MpscConsumerGuard<'_>) -> bool {
unsafe {
let clear = this.shared.clear.get();
if !matches!(&*clear, MpscClearState::Reached(_)) { return false; }
let MpscClearState::Reached(endpoint) = clear.replace(MpscClearState::Transferring) else {
std::process::abort();
};
clear.write(MpscClearState::Available(endpoint));
}
true
}
#[allow(unused_variables)]
fn mpsc_consumer_drop_inner(this: &mut MpscConsumerGuard<'_>) {
if let Some(endpoint) = this.endpoint.take() {
unsafe {
let clear = this.shared.clear.get();
if !matches!(&*clear, MpscClearState::Transferring) { std::process::abort(); }
clear.write(MpscClearState::Available(endpoint));
}
}
let handed_off = std::mem::replace(&mut this.handed_off, 0);
this.shared.return_count(handed_off);
drop(this.consumer.take());
}
#[allow(unused_variables)]
fn mpsc_completion_new_inner(shared: &MpscQueueShared) -> MpscCompletionGuard<'_> {
MpscCompletionGuard { shared, armed: false }
}
#[allow(unused_variables)]
fn mpsc_completion_arm_inner(this: &mut MpscCompletionGuard<'_>) {
this.armed = true;
}
#[allow(unused_variables)]
fn mpsc_completion_drop_inner(this: &mut MpscCompletionGuard<'_>) -> bool {
std::mem::replace(&mut this.armed, false)
}
#[allow(unused_variables)]
fn mpsc_cleanup_new_inner(
shared: &MpscQueueShared,
resume_source: bool,
) -> MpscCleanupGuard<'_> {
MpscCleanupGuard {
shared,
pending: VecDeque::new(),
current: false,
resume_source,
}
}
#[allow(unused_variables)]
fn mpsc_cleanup_prepare_inner(this: &mut MpscCleanupGuard<'_>, capacity: usize) {
this.pending.reserve(capacity);
}
#[allow(unused_variables)]
fn mpsc_cleanup_drain_inner(this: &mut MpscCleanupGuard<'_>) {
while let Some(task) = this.pending.pop_front() {
this.current = true;
drop(task);
this.shared.return_count(1);
this.current = false;
}
}
#[allow(unused_variables)]
fn mpsc_cleanup_disarm_inner(this: &mut MpscCleanupGuard<'_>) {
this.resume_source = false;
}
#[allow(unused_variables)]
fn mpsc_cleanup_drop_inner(this: &mut MpscCleanupGuard<'_>) {
use std::sync::atomic::Ordering::AcqRel;
if this.current {
this.current = false;
this.shared.return_count(1);
}
while let Some(task) = this.pending.pop_front() {
this.current = true;
drop(task);
this.shared.return_count(1);
this.current = false;
}
if this.resume_source { mpsc_request_cleanup_inner(this.shared); }
while this.resume_source {
let mut progressed = false;
let mut task = None;
let Some(mut consumer) = MpscConsumerGuard::try_new(this.shared) else {
this.resume_source = false;
break;
};
let state = this.shared.state.fetch_and(!CLEANUP_REQUESTED, AcqRel);
if state & COUNT_MASK == 0 { progressed |= consumer.acknowledge_clear(); }
let mut empty = false;
let mut deferred = false;
match consumer.try_take() {
Ok(Some(value)) => task = Some(value),
Ok(None) => {
progressed = true;
if this.shared.state.fetch_or(0, AcqRel) & COUNT_MASK == 0 {
progressed |= consumer.acknowledge_clear();
}
}
Err(TryDequeueError::Empty) => empty = true,
Err(TryDequeueError::Inconsistent) => deferred = true,
Err(TryDequeueError::Busy) => std::process::abort(),
}
let endpoint_available = unsafe {
matches!(&*this.shared.clear.get(), MpscClearState::Available(_))
};
drop(consumer);
if let Some(task) = task {
this.current = true;
drop(task);
this.shared.return_count(1);
this.current = false;
progressed = true;
}
if progressed { mpsc_request_cleanup_inner(this.shared); }
let state = this.shared.state.fetch_or(0, AcqRel);
if empty && endpoint_available && state & COUNT_MASK == 0 {
this.resume_source = false;
} else if progressed || state & CLEANUP_REQUESTED != 0 {
continue;
} else if empty || deferred {
this.resume_source = false;
}
}
}