Bellow simplified version of my code.
When tokio
notify me about some event, I want to run my code (in real world I recieve data
from channel, for simplification here I do just let data = Data
).
The problem is the Cache
is possible to use only in one thread simultaneously, and Cache::save
is blocking.
I try my best, but code still impossible to compile.
The problem that I have MutexGuard
after Mutex::lock
and I can not use it several times.
tokio_threadpool::blocking
accepts FnOnce
so it is fine,
but poll_fn
accepts FnMut
and compiler not like it.
Of course I can write my poll_fn
that accept FnOnce
instead of FnMut
,
but how I implement Future
for it? Future::poll
can obviously run several times?
use futures::{
future::{poll_fn, Future},
stream::Stream,
sync::BiLock,
};
use std::path::Path;
fn main() {
let cache = futures_locks::Mutex::new(Cache::new(Path::new("/tmp/cache.txt")));
let fut = cache.lock().and_then(move |mut guard| {
let data = Data;
poll_fn(move || {
tokio_threadpool::blocking(move || {
println!("another thread");
guard.save(data).unwrap();
})
.map_err(|_| panic!("the threadpool shut down"))
})
});
}
struct Data;
struct Cache {
_marker: std::cell::UnsafeCell<()>,
}
impl Cache {
fn new(path: &Path) -> Cache {
unimplemented!();
}
fn save(&mut self, data: Data) -> Result<(), ()> {
unimplemented!();
}
}