atomr_accel_cuda/stream/
pool.rs1use std::sync::Arc;
9
10use cudarc::driver::{CudaContext, CudaStream};
11
12use super::{ActorHints, StreamAllocator};
13
14pub struct PooledAllocator {
15 pool: Vec<Arc<CudaStream>>,
16 cursor: parking_lot::Mutex<usize>,
17}
18
19impl PooledAllocator {
20 pub fn new(streams: Vec<Arc<CudaStream>>) -> Self {
23 assert!(
24 !streams.is_empty(),
25 "PooledAllocator requires at least one stream"
26 );
27 Self {
28 pool: streams,
29 cursor: parking_lot::Mutex::new(0),
30 }
31 }
32
33 pub fn with_size(ctx: &Arc<CudaContext>, count: usize) -> Self {
37 assert!(count > 0, "PooledAllocator requires count >= 1");
38 let mut streams = Vec::with_capacity(count);
39 for _ in 0..count {
40 let s = ctx
41 .new_stream()
42 .unwrap_or_else(|e| panic!("ContextPoisoned: new_stream: {e}"));
43 streams.push(s);
44 }
45 Self::new(streams)
46 }
47
48 pub fn size(&self) -> usize {
49 self.pool.len()
50 }
51}
52
53impl StreamAllocator for PooledAllocator {
54 fn acquire(&self, _hints: ActorHints) -> Arc<CudaStream> {
55 let mut cur = self.cursor.lock();
56 let idx = *cur % self.pool.len();
57 *cur = cur.wrapping_add(1);
58 self.pool[idx].clone()
59 }
60}