mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-08-16 00:00:12 +02:00
Provides a thread pool dedicated to running blocking operations (#588) and update `tokio-fs` to use this pool. In an effort to make incremental progress, this is an initial step towards a final solution. First, it provides a very basic pool implementation with the intend that the pool will be replaced before the final release. Second, it updates `tokio-fs` to always use this blocking pool instead of conditionally using `threadpool::blocking`. Issue #588 contains additional discussion around potential improvements to the "blocking for all" strategy. The implementation provided here builds on work started in #954 and continued in #1045. The general idea is th same as #1045, but the PR improves on some of the details: * The number of explicit operations tracked by `File` is reduced only to the ones that could interact. All other ops are spawned on the blocking pool without being tracked by the `File` instance. * The `seek` implementation is not backed by a trait and `poll_seek` function. This avoids the question of how to model non-blocking seeks on top of a blocking file. In this patch, `seek` is represented as an `async fn`. If the associated future is dropped before the caller observes the return value, we make no effort to define the state in which the file ends up.
67 lines
1.4 KiB
Rust
67 lines
1.4 KiB
Rust
use tokio_sync::oneshot;
|
|
|
|
use std::cell::RefCell;
|
|
use std::collections::VecDeque;
|
|
use std::future::Future;
|
|
use std::io;
|
|
use std::pin::Pin;
|
|
use std::task::{Context, Poll};
|
|
|
|
thread_local! {
|
|
static QUEUE: RefCell<VecDeque<Box<dyn FnOnce() + Send>>> = RefCell::new(VecDeque::new())
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub(crate) struct Blocking<T> {
|
|
rx: oneshot::Receiver<T>,
|
|
}
|
|
|
|
pub(crate) fn run<F, R>(f: F) -> Blocking<R>
|
|
where
|
|
F: FnOnce() -> R + Send + 'static,
|
|
R: Send + 'static,
|
|
{
|
|
let (tx, rx) = oneshot::channel();
|
|
let task = Box::new(move || {
|
|
let _ = tx.send(f());
|
|
});
|
|
|
|
QUEUE.with(|cell| cell.borrow_mut().push_back(task));
|
|
|
|
Blocking { rx }
|
|
}
|
|
|
|
impl<T> Future for Blocking<T> {
|
|
type Output = T;
|
|
|
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
|
use std::task::Poll::*;
|
|
|
|
match Pin::new(&mut self.rx).poll(cx) {
|
|
Ready(Ok(v)) => Ready(v),
|
|
Ready(Err(e)) => panic!("error = {:?}", e),
|
|
Pending => Pending,
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) async fn asyncify<F, T>(f: F) -> io::Result<T>
|
|
where
|
|
F: FnOnce() -> io::Result<T> + Send + 'static,
|
|
T: Send + 'static,
|
|
{
|
|
run(f).await
|
|
}
|
|
|
|
pub(crate) fn len() -> usize {
|
|
QUEUE.with(|cell| cell.borrow().len())
|
|
}
|
|
|
|
pub(crate) fn run_one() {
|
|
let task = QUEUE
|
|
.with(|cell| cell.borrow_mut().pop_front())
|
|
.expect("expected task to run, but none ready");
|
|
|
|
task();
|
|
}
|