pub struct Pool { /* private fields */ }Expand description
Managing access to N equivalent resources
Callers who wish to access a resource (but don’t care which one of the N)
can call the async function Pool::alloc which will return (awakening
the task) as soon as a resource is available.
Once the returned resource (represented as a Pooled) is
finished with, the caller can then drop it (i.e., let it go out of
scope) and it will be returned to the pool for another user.
Not quite the same as async_semaphore, because callers need to know which of the N devices they were allotted.
§Example
use cotton_usb_host::async_pool::Pool;
let mut pool = Pool::new(2); // this pool has two resources
let res = pool.try_alloc().unwrap(); // obtain a resource
println!("I got resource {}", res.which());
{
let res2 = pool.try_alloc().unwrap(); // obtain a resource
println!("I got resource {}", res.which());
let res3 = pool.try_alloc();
assert!(res3.is_none()); // oh dear, no resources available
// But now res2 goes out of scope (i.e., back into the pool)
}
let res4 = pool.try_alloc().unwrap();
println!("I got resource {}", res.which()); // success!For a larger example, see how the RP2040 USB host-controller driver shares out its USB endpoints.
Implementations§
Source§impl Pool
impl Pool
Sourcepub async fn alloc(&self) -> Pooled<'_>
pub async fn alloc(&self) -> Pooled<'_>
Obtain one of the resources
This asynchronous function will return immediately if any of
the resources is currently idle (unused). Otherwise, it will
wait until a resource is available. Once it has returned, the
caller has ownership of the resource (represented by ownership
of the Pooled object) until the Pooled is dropped – for instance,
at the end of a scope.
It is not unsafe or unsound (in the Rust sense) to keep hold
of a Pooled indefinitely, nor to mem::forget it – but it is
inadvisable, as this constitutes a denial-of-service against
other potential resource users.
§See also
Pool::try_alloc() for a synchronous version