Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add spawn_pinned to tokio-util #3370

Merged
merged 47 commits into from Jan 27, 2022
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
9d0ee8d
Add Jetbrains IDE .idea folder to gitignore
AzureMarker Jan 3, 2021
34ccb19
tokio-util: add (incomplete) spawn_pinned support
AzureMarker Jan 3, 2021
1260d6f
Fix clippy warnings
AzureMarker Jan 3, 2021
4501084
Fix the rest of the clippy warnings
AzureMarker Jan 3, 2021
cfdbb8b
Ignore the spawn_pinned test for now because it doesn't terminate
AzureMarker Jan 3, 2021
9dd38b9
Replace global pool with owned handles to individual pools
AzureMarker Jan 4, 2021
af54d47
Add docs
AzureMarker Jan 4, 2021
a621591
Enforce a pool size of at least 1
AzureMarker Jan 5, 2021
0df5844
Track # of tasks in each worker and use least burdened in spawn_pinned
AzureMarker Jan 5, 2021
27df2b2
Add another test
AzureMarker Jan 5, 2021
e454f4f
Revert "Add Jetbrains IDE .idea folder to gitignore"
AzureMarker Sep 28, 2021
c073781
Merge branch 'master' into feature/spawn-pinned
AzureMarker Sep 28, 2021
0189798
Merge branch 'master' into feature/spawn-pinned
AzureMarker Oct 24, 2021
764414c
Replace spawn_blocking with std::thread::spawn
AzureMarker Oct 29, 2021
ff14408
Enable all features on the worker runtime
AzureMarker Oct 29, 2021
ca7f8e8
Fix giving more than one task to the least burdened worker
AzureMarker Oct 29, 2021
9486e32
Remove downcasting in spawn_pinned
AzureMarker Oct 29, 2021
2939338
Add spawn_pinned_nonblocking
AzureMarker Oct 29, 2021
ba8b6be
Fix doc link to spawn_pinned
AzureMarker Oct 30, 2021
c4cce06
Simplify spawn_pinned test
AzureMarker Nov 21, 2021
09839ad
Move LocalPoolHandle creation into LocalPoolHandle::new
AzureMarker Nov 21, 2021
24ca0c7
Simplify bounds on spawn_pinned functions
AzureMarker Nov 21, 2021
5444dda
Create local pool runtimes on user's thread in case it panics
AzureMarker Nov 21, 2021
45b5435
Tweak how join handle send error is dropped
AzureMarker Nov 21, 2021
75b9bb1
Fix some compile errors
AzureMarker Nov 21, 2021
e5972b0
Make spawn_pinned async and name blocking version spawn_pinned_blocking
AzureMarker Nov 25, 2021
4ce300f
Merge branch 'master' into feature/spawn-pinned
AzureMarker Nov 25, 2021
4622c2a
Make spawn_pinned synchronous again, but immediately send the task
AzureMarker Nov 25, 2021
e8e7af9
Fix broken link in docs
AzureMarker Nov 25, 2021
bd32346
Synchronously return join handle in spawn_pinned
AzureMarker Nov 26, 2021
7769e0a
Simplify channel types
AzureMarker Nov 26, 2021
b64edff
Use catch_unwind and AssertUnwindSafe to protect workers from panics
AzureMarker Dec 3, 2021
bb6bdb1
Call create_task in spawn_local to avoid using catch_unwind ourselves
AzureMarker Dec 4, 2021
ff7ad94
Directly resume panic unwinding if the task panics
AzureMarker Dec 4, 2021
5e21d68
Automatically decrement job count via guard (Drop impl)
AzureMarker Dec 5, 2021
b7c4da9
Propagate task cancellation in spawn_pinned
AzureMarker Dec 5, 2021
2067c61
Propagate task cancellation in one more spot (very unlikely to occur)
AzureMarker Dec 5, 2021
16e1521
Minor renaming/formatting
AzureMarker Dec 5, 2021
62f5ec7
Add a test to ensure tasks are balanced across workers
AzureMarker Dec 21, 2021
c130046
Use a robust abort handling mechanism
AzureMarker Dec 21, 2021
8aaa3ca
Fix typo (missing word)
AzureMarker Dec 28, 2021
9214302
Return job count guard when incrementing worker
AzureMarker Dec 29, 2021
1bd5bf2
Add a debug assert to verify the job count doesn't go negative
AzureMarker Dec 29, 2021
34d3646
Check against panic message in tests
AzureMarker Dec 29, 2021
2937f7e
Remove sleeps in spawn_pinned tests
AzureMarker Dec 29, 2021
5d9bbde
Update tokio-util/src/task/spawn_pinned.rs
AzureMarker Dec 29, 2021
fb11c45
Fix some compile errors after applying suggestion
AzureMarker Dec 29, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
@@ -1,2 +1,5 @@
target
Cargo.lock

AzureMarker marked this conversation as resolved.
Show resolved Hide resolved
## Jetbrains IDEs
/.idea/
2 changes: 1 addition & 1 deletion tokio-util/Cargo.toml
Expand Up @@ -31,7 +31,7 @@ compat = ["futures-io",]
codec = []
time = ["tokio/time","slab"]
io = []
rt = ["tokio/rt"]
rt = ["tokio/rt", "tokio/sync"]

__docs_rs = ["futures-util"]

Expand Down
1 change: 1 addition & 0 deletions tokio-util/src/lib.rs
Expand Up @@ -44,6 +44,7 @@ cfg_io! {

cfg_rt! {
pub mod context;
pub mod task;
}

pub mod sync;
Expand Down
4 changes: 4 additions & 0 deletions tokio-util/src/task/mod.rs
@@ -0,0 +1,4 @@
//! Extra utilities for spawning tasks

mod spawn_pinned;
pub use spawn_pinned::{new_local_pool, LocalPoolHandle};
184 changes: 184 additions & 0 deletions tokio-util/src/task/spawn_pinned.rs
@@ -0,0 +1,184 @@
use std::any::Any;
use std::fmt;
use std::fmt::{Debug, Formatter};
use std::future::Future;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender};
use std::sync::Arc;
use tokio::runtime::Builder;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::task::{spawn_blocking, spawn_local, JoinHandle, LocalSet};

/// Create a new pool of threads to handle `!Send` tasks. Spawn tasks onto this
/// pool via [`LocalPoolHandle::spawn_pinned`].
pub fn new_local_pool(pool_size: usize) -> LocalPoolHandle {
assert!(pool_size > 0);

let workers = (0..pool_size)
.map(|_| LocalWorkerHandle::new_worker())
.collect();

let pool = Arc::new(LocalPool { workers });

LocalPoolHandle { pool }
}
AzureMarker marked this conversation as resolved.
Show resolved Hide resolved

/// A handle to a local pool created by [`new_local_pool`]
#[derive(Clone)]
pub struct LocalPoolHandle {
pool: Arc<LocalPool>,
}

impl LocalPoolHandle {
/// Spawn a task onto a worker thread and pin it there so it can't be moved
/// off of the thread. Note that the future is not Send, but the `FnOnce` which
/// creates it is.
///
/// # Examples
///
/// ```
/// use std::rc::Rc;
/// use tokio_util::task::new_local_pool;
///
/// #[tokio::main]
/// async fn main() {
/// // Create the local pool
/// let pool = new_local_pool(1);
///
/// // Spawn a !Send future onto the pool and await it
/// let output = pool
/// .spawn_pinned(|| {
/// // Rc is !Send + !Sync
/// let local_data = Rc::new("test");
///
/// // This future holds an Rc, so it is !Send
/// async move { local_data.to_string() }
/// })
/// .await
/// .unwrap();
///
/// assert_eq!(output, "test");
/// }
/// ```
pub fn spawn_pinned<Fut: Future + 'static>(
&self,
create_task: impl FnOnce() -> Fut + Send + 'static,
) -> JoinHandle<Fut::Output>
where
Fut::Output: Send + 'static,
{
AzureMarker marked this conversation as resolved.
Show resolved Hide resolved
self.pool.spawn_pinned(create_task)
}
}

impl Debug for LocalPoolHandle {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str("LocalPoolHandle")
}
}

struct LocalPool {
workers: Vec<LocalWorkerHandle>,
}

impl LocalPool {
/// Spawn a `?Send` future onto a worker
fn spawn_pinned<Fut: Future + 'static>(
&self,
create_task: impl FnOnce() -> Fut + Send + 'static,
) -> JoinHandle<Fut::Output>
where
Fut::Output: Send + 'static,
AzureMarker marked this conversation as resolved.
Show resolved Hide resolved
{
let worker = self.find_least_burdened_worker();

// Update task count. Do this before sending the future to ensure that
// the call to `fetch_sub` does not underflow.
worker.task_count.fetch_add(1, Ordering::SeqCst);
AzureMarker marked this conversation as resolved.
Show resolved Hide resolved

// Send the future to the worker
let (sender, receiver) = channel();
let task_count = Arc::clone(&worker.task_count);
let request = FutureRequest {
func: Box::new(|| {
Box::new(spawn_local(async move {
let result = create_task().await;

// Update the task count once the future is finished
task_count.fetch_sub(1, Ordering::SeqCst);

result
}))
}),
reply: sender,
};
worker.spawner.send(request).unwrap();

// Get the join handle
let join_handle = receiver.recv().unwrap();
let join_handle: JoinHandle<Fut::Output> = *join_handle.downcast().unwrap();

join_handle
}

/// Find the worker with the least number of tasks
fn find_least_burdened_worker(&self) -> &LocalWorkerHandle {
let (worker, _) = self
.workers
.iter()
.map(|worker| (worker, worker.task_count.load(Ordering::SeqCst)))
.min_by_key(|&(_, count)| count)
.expect("There must be more than one worker");
worker
}
}

// We need to box the join handle and future spawning closure since they're
// generic and are going through a channel. The join handle will be downcast
// back into the correct type.
type BoxedJoinHandle = Box<dyn Any + Send + 'static>;
type PinnedFutureSpawner = Box<dyn FnOnce() -> BoxedJoinHandle + Send + 'static>;

struct FutureRequest {
func: PinnedFutureSpawner,
reply: Sender<BoxedJoinHandle>,
}
AzureMarker marked this conversation as resolved.
Show resolved Hide resolved

// Needed for the unwrap in LocalPool::spawn_pinned if sending fails
impl Debug for FutureRequest {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str("FutureRequest")
}
}

struct LocalWorkerHandle {
spawner: UnboundedSender<FutureRequest>,
task_count: Arc<AtomicUsize>,
}

impl LocalWorkerHandle {
/// Create a new worker for executing pinned tasks
fn new_worker() -> LocalWorkerHandle {
let (sender, receiver) = unbounded_channel();
spawn_blocking(|| Self::run(receiver));
AzureMarker marked this conversation as resolved.
Show resolved Hide resolved

LocalWorkerHandle {
spawner: sender,
task_count: Arc::new(AtomicUsize::new(0)),
}
}

fn run(mut task_receiver: UnboundedReceiver<FutureRequest>) {
let runtime = Builder::new_current_thread()
.build()
.expect("Failed to start a pinned worker thread runtime");
AzureMarker marked this conversation as resolved.
Show resolved Hide resolved

LocalSet::new().block_on(&runtime, async {
while let Some(task) = task_receiver.recv().await {
// Calls spawn_local(future)
let join_handle = (task.func)();
task.reply.send(join_handle).unwrap();
}
});
}
}
52 changes: 52 additions & 0 deletions tokio-util/tests/spawn_pinned.rs
@@ -0,0 +1,52 @@
#![warn(rust_2018_idioms)]

use futures::{FutureExt, TryFutureExt};
use std::rc::Rc;
use tokio_util::task;

#[tokio::test]
async fn can_spawn_not_send_future() {
let pool = task::new_local_pool(1);

let output = pool
.spawn_pinned(|| {
// Rc is !Send + !Sync
let local_data = Rc::new("test");

// This future holds an Rc, so it is !Send
async move { local_data.to_string() }
})
.await
.unwrap();

assert_eq!(output, "test");
}

#[test]
#[should_panic(expected = "assertion failed: pool_size > 0")]
fn cannot_create_zero_sized_pool() {
let _pool = task::new_local_pool(0);
}

#[tokio::test]
async fn can_spawn_multiple_futures() {
let pool = task::new_local_pool(2);

let future1 = pool
.spawn_pinned(|| {
let local_data = Rc::new("test1");
async move { local_data.to_string() }
})
.unwrap_or_else(|e| panic!("Join error: {}", e));
let future2 = pool
.spawn_pinned(|| {
let local_data = Rc::new("test2");
async move { local_data.to_string() }
})
.unwrap_or_else(|e| panic!("Join error: {}", e));
let joined_future =
futures::future::join(future1, future2).map(|(str1, str2)| format!("{} {}", str1, str2));

let output = joined_future.await;
assert_eq!(output, "test1 test2");
AzureMarker marked this conversation as resolved.
Show resolved Hide resolved
}