fix(metal): Wait using a condition variable instead of polling

Fixes #8119
This commit is contained in:
39ali authored and Andy Leiserson committed 2026-06-04 17:11:59 -07:00
1 parent 6e8d0bd149
commit e0a6065c65
3 files changed
+40 -43

No files matched your search

+2
View File
@@ -242,6 +242,8 @@ By @beholdnec in [#8505](https://github.com/gfx-rs/wgpu/pull/8505).
#### Metal
- Fix crash on fence creation when running in a MacOS Seatbelt sandbox. By @wumpf in [#9415](https://github.com/gfx-rs/wgpu/pull/9415)
- Improved command buffer completion handling. By @39ali in [#9328](https://github.com/gfx-rs/wgpu/pull/9328).
- Wait using a condition variable, instead of polling.
- Fixed structure field names incorrectly ignoring reserved keywords in the Metal (MSL) backend. By @39ali [#9379](https://github.com/gfx-rs/wgpu/pull/9379).
- Restore the `Queue::as_raw` method, which was removed without good reason in v29. It now returns `&ProtocolObject<dyn MTLCommandQueue>`. By @andyleiserson in [#9560](https://github.com/gfx-rs/wgpu/pull/9560).
+32 -38
View File
@@ -1,7 +1,5 @@
use alloc::{borrow::ToOwned as _, sync::Arc, vec::Vec};
use core::{ptr::NonNull, sync::atomic};
use parking_lot::RwLock;
use std::{thread, time};
use core::ptr::NonNull;
use bytemuck::TransparentWrapper;
use objc2::{
@@ -12,11 +10,11 @@ use objc2::{
use objc2_foundation::{ns_string, NSError, NSRange, NSString, NSUInteger};
use objc2_metal::{
MTLAccelerationStructure, MTLAccelerationStructureInstanceOptions, MTLBuffer,
MTLCaptureManager, MTLCaptureScope, MTLCommandBuffer, MTLCommandBufferStatus,
MTLCompileOptions, MTLComputePipelineDescriptor, MTLComputePipelineState,
MTLCounterSampleBufferDescriptor, MTLCounterSet, MTLDepthClipMode, MTLDepthStencilDescriptor,
MTLDevice, MTLFunction, MTLIndirectAccelerationStructureInstanceDescriptor, MTLLanguageVersion,
MTLLibrary, MTLMeshRenderPipelineDescriptor, MTLMutability, MTLPackedFloat3, MTLPackedFloat4x3,
MTLCaptureManager, MTLCaptureScope, MTLCompileOptions, MTLComputePipelineDescriptor,
MTLComputePipelineState, MTLCounterSampleBufferDescriptor, MTLCounterSet, MTLDepthClipMode,
MTLDepthStencilDescriptor, MTLDevice, MTLFunction,
MTLIndirectAccelerationStructureInstanceDescriptor, MTLLanguageVersion, MTLLibrary,
MTLMeshRenderPipelineDescriptor, MTLMutability, MTLPackedFloat3, MTLPackedFloat4x3,
MTLPipelineBufferDescriptorArray, MTLPipelineOption, MTLPixelFormat, MTLPrimitiveTopologyClass,
MTLRenderPipelineColorAttachmentDescriptorArray, MTLRenderPipelineDescriptor, MTLResource,
MTLResourceID, MTLResourceOptions, MTLSamplerAddressMode, MTLSamplerDescriptor,
@@ -24,6 +22,7 @@ use objc2_metal::{
MTLTexture, MTLTextureDescriptor, MTLTextureType, MTLTriangleFillMode, MTLVertexDescriptor,
MTLVertexStepFunction,
};
use parking_lot::{Condvar, Mutex, RwLock};
use super::{adapter::VERTEX_BUFFER_SLOT_START, conv, PassthroughShader, ShaderModuleSource};
use crate::{auxil::map_naga_stage, TlasInstance};
@@ -1886,7 +1885,7 @@ impl crate::Device for super::Device {
None
};
Ok(super::Fence {
completed_value: Arc::new(atomic::AtomicU64::new(0)),
sync: Arc::new((Mutex::new(0), Condvar::new())),
pending_command_buffers: RwLock::new(Vec::new()),
shared_event,
})
@@ -1897,14 +1896,7 @@ impl crate::Device for super::Device {
}
unsafe fn get_fence_value(&self, fence: &super::Fence) -> DeviceResult<crate::FenceValue> {
let mut max_value = fence.completed_value.load(atomic::Ordering::Acquire);
let pending_command_buffers = fence.pending_command_buffers.read();
for &(value, ref cmd_buf) in pending_command_buffers.iter() {
if cmd_buf.status() == MTLCommandBufferStatus::Completed {
max_value = value;
}
}
Ok(max_value)
Ok(fence.get_latest())
}
unsafe fn wait(
&self,
@@ -1912,38 +1904,40 @@ impl crate::Device for super::Device {
wait_value: crate::FenceValue,
timeout: Option<core::time::Duration>,
) -> DeviceResult<bool> {
if wait_value <= fence.completed_value.load(atomic::Ordering::Acquire) {
let (ref mutex, ref condvar) = *fence.sync;
let mut lock = mutex.lock();
if wait_value <= *lock {
return Ok(true);
}
let pending_command_buffers = fence.pending_command_buffers.read();
let cmd_buf = match pending_command_buffers
.iter()
.find(|&&(value, _)| value >= wait_value)
{
Some((_, cmd_buf)) => cmd_buf.clone(),
None => {
let pending_command_buffers = fence.pending_command_buffers.read();
if !pending_command_buffers
.iter()
.any(|&(value, _)| value >= wait_value)
{
log::error!("No active command buffers for fence value {wait_value}");
return Err(crate::DeviceError::Lost);
}
};
}
// Make sure that nothing is blocked during the actual wait.
drop(pending_command_buffers);
let start = time::Instant::now();
loop {
if let MTLCommandBufferStatus::Completed = cmd_buf.status() {
return Ok(true);
}
if let Some(timeout) = timeout {
if start.elapsed() >= timeout {
return Ok(false);
if let Some(deadline) =
timeout.and_then(|timeout| std::time::Instant::now().checked_add(timeout))
{
while *lock < wait_value {
let result = condvar.wait_until(&mut lock, deadline);
if result.timed_out() {
return Ok(*lock >= wait_value);
}
}
thread::sleep(core::time::Duration::from_millis(1));
} else {
while *lock < wait_value {
condvar.wait(&mut lock);
}
}
Ok(true)
}
unsafe fn start_graphics_debugger_capture(&self) -> bool {
+6 -5
View File
@@ -55,7 +55,7 @@ use objc2_metal::{
MTLTriangleFillMode, MTLWinding,
};
use objc2_quartz_core::CAMetalLayer;
use parking_lot::{Mutex, RwLock};
use parking_lot::{Condvar, Mutex, RwLock};
#[derive(Clone, Debug)]
pub struct Api;
@@ -542,9 +542,10 @@ impl crate::Queue for Queue {
) -> Result<(), crate::DeviceError> {
autoreleasepool(|_| {
let extra_command_buffer = {
let completed_value = Arc::clone(&signal_fence.completed_value);
let fence_sync = Arc::clone(&signal_fence.sync);
let block = block2::RcBlock::new(move |_cmd_buf| {
completed_value.store(signal_value, atomic::Ordering::Release);
*fence_sync.0.lock() = signal_value;
fence_sync.1.notify_all();
});
let raw = match command_buffers.last() {
@@ -1028,7 +1029,7 @@ unsafe impl Sync for QuerySet {}
#[derive(Debug)]
pub struct Fence {
completed_value: Arc<atomic::AtomicU64>,
sync: Arc<(Mutex<crate::FenceValue>, Condvar)>,
/// The pending fence values have to be ascending.
pending_command_buffers: RwLock<Vec<PendingCommandBuffer>>,
shared_event: Option<Retained<ProtocolObject<dyn MTLSharedEvent>>>,
@@ -1046,7 +1047,7 @@ unsafe impl Sync for Fence {}
impl Fence {
fn get_latest(&self) -> crate::FenceValue {
let mut max_value = self.completed_value.load(atomic::Ordering::Acquire);
let mut max_value = *self.sync.0.lock();
let pending_command_buffers = self.pending_command_buffers.read();
for &(value, ref cmd_buf) in pending_command_buffers.iter() {
if cmd_buf.status() == MTLCommandBufferStatus::Completed {