singe_cuda/stream/context.rs
1use std::{ptr, sync::Arc};
2
3use singe_cuda_sys::runtime;
4
5use super::{RawStream, RawStreamOwnership, Stream, StreamOptions};
6use crate::{
7 context::Context,
8 error::{Error, Result},
9 try_ffi,
10};
11
12impl Context {
13 /// Creates an asynchronous stream in this context and makes this context current on the calling thread.
14 ///
15 /// [`StreamOptions::flags`] sets the stream's synchronization with the legacy default stream:
16 ///
17 /// * [`StreamFlags::DEFAULT`](super::StreamFlags::DEFAULT): default stream creation behavior.
18 /// * [`StreamFlags::NON_BLOCKING`](super::StreamFlags::NON_BLOCKING): allows the created stream to run concurrently with the legacy default stream without implicit synchronization.
19 ///
20 /// [`StreamOptions::priority`] sets the scheduling priority of work in the stream.
21 /// Priorities are a hint to run higher-priority work first when possible; they do not preempt running work or otherwise order execution.
22 /// Lower numbers are higher priorities, and `0` is the default priority.
23 /// [`Device::stream_priority_range`](crate::device::Device::stream_priority_range) reports the meaningful range, and CUDA clamps a priority outside it to the nearest end.
24 /// Priorities affect only compute kernels, not host-to-device or device-to-host memory operations.
25 ///
26 /// # Errors
27 ///
28 /// Returns an error if the context cannot be bound, CUDA cannot create the stream, CUDA returns a null stream handle, a previous asynchronous launch reports an error, or CUDA reports runtime initialization diagnostics.
29 pub fn create_stream(self: &Arc<Self>, options: StreamOptions) -> Result<Stream> {
30 self.bind()?;
31 let mut handle = ptr::null_mut();
32 // SAFETY: `handle` is a writable local, and the context is bound above.
33 unsafe {
34 try_ffi!(runtime::cudaStreamCreateWithPriority(
35 &raw mut handle,
36 options.flags.bits(),
37 options.priority,
38 ))?;
39 }
40
41 if handle.is_null() {
42 return Err(Error::NullHandle);
43 }
44 // SAFETY: CUDA just created this handle in this context, and nothing else owns it.
45 unsafe {
46 Stream::from_raw(RawStream {
47 handle,
48 context: Arc::clone(self),
49 ownership: RawStreamOwnership::Owned,
50 })
51 }
52 }
53}