ocl_stream/utils/
shared_buffer.rs

1/*
2 * opencl stream executor
3 * Copyright (C) 2021 trivernis
4 * See LICENSE for more information
5 */
6use ocl::{Buffer, OclPrm};
7use parking_lot::Mutex;
8use std::any::type_name;
9use std::sync::Arc;
10
11#[derive(Clone)]
12pub struct SharedBuffer<T>
13where
14    T: OclPrm,
15{
16    inner: Arc<Mutex<Buffer<T>>>,
17}
18
19impl<T> SharedBuffer<T>
20where
21    T: OclPrm,
22{
23    /// Creates a new shared buffer with an inner ocl buffer
24    pub fn new(buf: Buffer<T>) -> Self {
25        Self {
26            inner: Arc::new(Mutex::new(buf)),
27        }
28    }
29
30    /// Writes into the buffer
31    pub fn write(&self, src: &[T]) -> ocl::Result<()> {
32        log::trace!("Writing into shared buffer of type {}", type_name::<T>());
33        let buffer = self.inner.lock();
34        buffer.write(src).enq()
35    }
36
37    /// Reads from the buffer
38    pub fn read(&self, dst: &mut [T]) -> ocl::Result<()> {
39        log::trace!("Reading from shared buffer of type {}", type_name::<T>());
40        let buffer = self.inner.lock();
41        buffer.read(dst).enq()
42    }
43
44    /// Returns the inner buffer
45    pub fn inner(&self) -> Arc<Mutex<Buffer<T>>> {
46        Arc::clone(&self.inner)
47    }
48}