1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use futures::{future, FutureExt, TryFutureExt};
use std::{
	future::Future, io, panic::{RefUnwindSafe, UnwindSafe}, sync::Arc
};
use tokio::task::spawn;

use super::util::{assert_sync_and_send, Panicked};

const DEFAULT_TASKS_PER_CORE: usize = 100;

#[derive(Debug)]
struct ThreadPoolInner {
	logical_cores: usize,
	tasks_per_core: usize,
}

#[derive(Debug)]
pub struct ThreadPool(Arc<ThreadPoolInner>);
impl ThreadPool {
	pub fn new(tasks_per_core: Option<usize>) -> io::Result<Self> {
		let logical_cores = num_cpus::get();
		let tasks_per_core = tasks_per_core.unwrap_or(DEFAULT_TASKS_PER_CORE);
		Ok(ThreadPool(Arc::new(ThreadPoolInner {
			logical_cores,
			tasks_per_core,
		})))
	}
	pub fn threads(&self) -> usize {
		self.0.logical_cores * self.0.tasks_per_core
	}
	pub fn spawn<F, Fut, T>(&self, work: F) -> impl Future<Output = Result<T, Panicked>> + Send
	where
		F: FnOnce() -> Fut + Send + 'static,
		Fut: Future<Output = T> + 'static,
		T: Send + 'static,
	{
		let _self = self;
		spawn(DuckSend(future::lazy(|_| work()).flatten()))
			.map_err(tokio::task::JoinError::into_panic)
			.map_err(Panicked::from)
	}
}

impl Clone for ThreadPool {
	/// Cloning a pool will create a new handle to the pool.
	/// The behavior is similar to [Arc](https://doc.rust-lang.org/stable/std/sync/struct.Arc.html).
	///
	/// We could for example submit jobs from multiple threads concurrently.
	fn clone(&self) -> Self {
		Self(self.0.clone())
	}
}

impl UnwindSafe for ThreadPool {}
impl RefUnwindSafe for ThreadPool {}

fn _assert() {
	let _ = assert_sync_and_send::<ThreadPool>;
}

// TODO remove when spawn_pinned exists https://github.com/tokio-rs/tokio/issues/2545

use pin_project::pin_project;
use std::{
	pin::Pin, task::{Context, Poll}
};
#[pin_project]
struct DuckSend<F>(#[pin] F);
impl<F> Future for DuckSend<F>
where
	F: Future,
{
	type Output = F::Output;

	fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
		// TODO!
		// assert!(<F as IsSend>::is_send(), "{}", std::any::type_name::<F>());
		self.project().0.poll(cx)
	}
}
#[allow(unsafe_code)]
unsafe impl<F> Send for DuckSend<F> {}

trait IsSend {
	fn is_send() -> bool;
}
impl<T: ?Sized> IsSend for T {
	default fn is_send() -> bool {
		false
	}
}
impl<T: ?Sized> IsSend for T
where
	T: Send,
{
	fn is_send() -> bool {
		true
	}
}