use std::sync::Arc;
use cudarc::driver::safe::{
CudaEvent, CudaFunction, CudaStream, DriverError, LaunchArgs, LaunchConfig, PushKernelArg,
};
use super::lock::{DeviceCaptureLock, EnqueuePermit, device_lock};
#[derive(Clone)]
pub struct GuardedStream {
stream: Arc<CudaStream>,
device_index: usize,
lock: DeviceCaptureLock,
}
impl std::fmt::Debug for GuardedStream {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GuardedStream")
.field("device_index", &self.device_index)
.finish_non_exhaustive()
}
}
impl GuardedStream {
pub(crate) fn new(stream: Arc<CudaStream>, device_index: usize) -> Self {
let lock = device_lock(device_index);
Self {
stream,
device_index,
lock,
}
}
#[inline]
pub fn launch_builder<'a>(&'a self, func: &'a CudaFunction) -> GuardedLaunchBuilder<'a> {
GuardedLaunchBuilder {
inner: self.stream.launch_builder(func),
lock: &self.lock,
device_index: self.device_index,
}
}
#[inline]
pub fn enqueue_permit(&self) -> EnqueuePermit<'_> {
EnqueuePermit::acquire(&self.lock, self.device_index)
}
pub fn synchronize(&self) -> Result<(), DriverError> {
let _permit = self.enqueue_permit();
self.stream.synchronize()
}
#[inline]
pub fn raw(&self) -> &CudaStream {
&self.stream
}
#[inline]
pub fn arc(&self) -> &Arc<CudaStream> {
&self.stream
}
#[inline]
pub fn device_index(&self) -> usize {
self.device_index
}
#[inline]
pub(crate) fn capture_lock(&self) -> &DeviceCaptureLock {
&self.lock
}
}
pub struct GuardedLaunchBuilder<'a> {
inner: LaunchArgs<'a>,
lock: &'a std::sync::RwLock<()>,
device_index: usize,
}
unsafe impl<'a, T> PushKernelArg<T> for GuardedLaunchBuilder<'a>
where
LaunchArgs<'a>: PushKernelArg<T>,
{
#[inline(always)]
fn arg(&mut self, arg: T) -> &mut Self {
self.inner.arg(arg);
self
}
}
impl GuardedLaunchBuilder<'_> {
#[inline]
pub unsafe fn launch(
&mut self,
cfg: LaunchConfig,
) -> Result<Option<(CudaEvent, CudaEvent)>, DriverError> {
let _permit = EnqueuePermit::acquire(self.lock, self.device_index);
unsafe { self.inner.launch(cfg) }
}
}