allow spawning a future from another thread
The future will be polled by the gui thread. I'm not totally convinced that this model is best.
This commit is contained in:
1 parent
d71ac26b93
commit
5dfa5bca6b
4 files changed
+91
-12
No files matched your search
+63
-6
@@ -15,11 +15,15 @@ use futures::executor::{self, Notify, Spawn};
|
||||
use futures::future::{ExecuteError, Executor};
|
||||
use futures::{Async, Future};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
const EXTERNAL_SPAWN: usize = !0usize;
|
||||
|
||||
pub trait CoreSender: Send {
|
||||
fn send(&self, idx: usize) -> Result<(), Error>;
|
||||
fn clone_sender(&self) -> Box<CoreSender>;
|
||||
}
|
||||
|
||||
pub trait CoreReceiver {
|
||||
@@ -35,6 +39,34 @@ pub struct Core {
|
||||
// future is ready to get polled.
|
||||
tasks: RefCell<Vec<Slot>>,
|
||||
next_vacant: Cell<usize>,
|
||||
external_spawn: Arc<SpawningFromAnotherThread>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SpawningFromAnotherThread {
|
||||
futures: Mutex<VecDeque<Box<Future<Item = (), Error = ()> + Send>>>,
|
||||
}
|
||||
|
||||
pub struct Spawner {
|
||||
tx: Box<CoreSender>,
|
||||
external_spawn: Arc<SpawningFromAnotherThread>,
|
||||
}
|
||||
|
||||
impl Spawner {
|
||||
pub fn spawn(&self, future: Box<dyn Future<Item = (), Error = ()> + Send>) {
|
||||
let mut futures = self.external_spawn.futures.lock().unwrap();
|
||||
futures.push_back(future);
|
||||
self.tx.send(EXTERNAL_SPAWN).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Spawner {
|
||||
fn clone(&self) -> Spawner {
|
||||
Spawner {
|
||||
tx: self.tx.clone_sender(),
|
||||
external_spawn: Arc::clone(&self.external_spawn),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Slot {
|
||||
@@ -43,7 +75,8 @@ enum Slot {
|
||||
}
|
||||
|
||||
impl Core {
|
||||
pub fn new(tx: Box<CoreSender>, tx2: Box<CoreSender>, rx: Box<CoreReceiver>) -> Self {
|
||||
pub fn new(tx: Box<CoreSender>, rx: Box<CoreReceiver>) -> Self {
|
||||
let tx2 = tx.clone_sender();
|
||||
Self {
|
||||
notify: Arc::new(Notifier {
|
||||
tx: Mutex::new(tx2),
|
||||
@@ -52,6 +85,14 @@ impl Core {
|
||||
rx,
|
||||
next_vacant: Cell::new(0),
|
||||
tasks: RefCell::new(Vec::new()),
|
||||
external_spawn: Arc::new(SpawningFromAnotherThread::default()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_spawner(&self) -> Spawner {
|
||||
Spawner {
|
||||
tx: self.tx.clone_sender(),
|
||||
external_spawn: Arc::clone(&self.external_spawn),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +103,10 @@ impl Core {
|
||||
where
|
||||
F: Future<Item = (), Error = ()> + 'static,
|
||||
{
|
||||
self.spawn_impl(Box::new(f), true);
|
||||
}
|
||||
|
||||
fn spawn_impl(&self, f: Box<Future<Item = (), Error = ()> + 'static>, do_tx: bool) -> usize {
|
||||
let idx = self.next_vacant.get();
|
||||
let mut tasks = self.tasks.borrow_mut();
|
||||
match tasks.get_mut(idx) {
|
||||
@@ -76,7 +121,19 @@ impl Core {
|
||||
}
|
||||
}
|
||||
tasks[idx] = Slot::RunningFuture(Some(executor::spawn(Box::new(f))));
|
||||
self.tx.send(idx).unwrap();
|
||||
if do_tx {
|
||||
self.tx.send(idx).unwrap();
|
||||
}
|
||||
idx
|
||||
}
|
||||
|
||||
fn spawn_external(&self) -> Option<usize> {
|
||||
let mut futures = self.external_spawn.futures.lock().unwrap();
|
||||
if let Some(future) = futures.pop_front() {
|
||||
Some(self.spawn_impl(future, false))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// "Turns" this event loop one tick.
|
||||
@@ -84,6 +141,10 @@ impl Core {
|
||||
/// Returns `false` if there were no futures in a known-ready state.
|
||||
pub fn turn(&self) -> bool {
|
||||
let task_id = match self.rx.try_recv() {
|
||||
Ok(task_id) if task_id == EXTERNAL_SPAWN => match self.spawn_external() {
|
||||
Some(task_id) => task_id,
|
||||
_ => return false,
|
||||
},
|
||||
Ok(task_id) => task_id,
|
||||
Err(mpsc::TryRecvError::Empty) => return false,
|
||||
Err(mpsc::TryRecvError::Disconnected) => panic!("futurecore rx Disconnected"),
|
||||
@@ -132,10 +193,6 @@ where
|
||||
}
|
||||
|
||||
struct Notifier {
|
||||
// TODO: it's pretty unfortunate to use a `Mutex` here where the `Sender`
|
||||
// itself is basically `Sync` as-is. Ideally this'd use something like
|
||||
// an off-the-shelf mpsc queue as well as `thread::park` and
|
||||
// `Thread::unpark`.
|
||||
tx: Mutex<Box<CoreSender>>,
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,9 @@ impl futurecore::CoreSender for GuiSender<usize> {
|
||||
fn send(&self, idx: usize) -> Result<(), Error> {
|
||||
GuiSender::send(self, idx)
|
||||
}
|
||||
fn clone_sender(&self) -> Box<futurecore::CoreSender> {
|
||||
Box::new(GuiSender::clone(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl PtyEventSender for GuiSender<PtyEvent> {
|
||||
@@ -154,8 +157,8 @@ impl GuiEventLoop {
|
||||
let event_loop = glium::glutin::EventsLoop::new();
|
||||
|
||||
let (fut_tx, fut_rx) = channel(event_loop.create_proxy());
|
||||
let fut_tx2 = fut_tx.clone();
|
||||
let core = futurecore::Core::new(Box::new(fut_tx), Box::new(fut_tx2), Box::new(fut_rx));
|
||||
let core = futurecore::Core::new(Box::new(fut_tx), Box::new(fut_rx));
|
||||
mux.set_spawner(core.get_spawner());
|
||||
|
||||
let (poll_tx, poll_rx) = channel(event_loop.create_proxy());
|
||||
|
||||
|
||||
+5
-2
@@ -25,6 +25,9 @@ impl futurecore::CoreSender for GuiSender<usize> {
|
||||
fn send(&self, idx: usize) -> Result<(), Error> {
|
||||
GuiSender::send(self, idx).map_err(|e| format_err!("send: {}", e))
|
||||
}
|
||||
fn clone_sender(&self) -> Box<futurecore::CoreSender> {
|
||||
Box::new(GuiSender::clone(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl PtyEventSender for GuiSender<PtyEvent> {
|
||||
@@ -103,8 +106,8 @@ impl GuiEventLoop {
|
||||
Ready::readable(),
|
||||
PollOpt::level(),
|
||||
)?;
|
||||
let fut_tx2 = fut_tx.clone();
|
||||
let core = futurecore::Core::new(Box::new(fut_tx), Box::new(fut_tx2), Box::new(fut_rx));
|
||||
let core = futurecore::Core::new(Box::new(fut_tx), Box::new(fut_rx));
|
||||
mux.set_spawner(core.get_spawner());
|
||||
|
||||
let (pty_tx, pty_rx) = channel();
|
||||
poll.register(&pty_rx, Token(TOK_PTY), Ready::readable(), PollOpt::level())?;
|
||||
|
||||
+18
-2
@@ -1,3 +1,4 @@
|
||||
use crate::futurecore::Spawner;
|
||||
use crate::guicommon::tabs::{Tab, TabId};
|
||||
use failure::Error;
|
||||
use std::cell::RefCell;
|
||||
@@ -13,6 +14,7 @@ pub mod renderable;
|
||||
#[derive(Default)]
|
||||
pub struct Mux {
|
||||
tabs: RefCell<HashMap<TabId, Rc<Tab>>>,
|
||||
spawner: RefCell<Option<Spawner>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -25,7 +27,12 @@ pub trait PtyEventSender: Send {
|
||||
fn send(&self, event: PtyEvent) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
fn read_from_tab_pty(sender: Box<PtyEventSender>, tab_id: TabId, mut reader: Box<std::io::Read>) {
|
||||
fn read_from_tab_pty(
|
||||
spawner: Spawner,
|
||||
sender: Box<PtyEventSender>,
|
||||
tab_id: TabId,
|
||||
mut reader: Box<std::io::Read>,
|
||||
) {
|
||||
const BUFSIZE: usize = 32 * 1024;
|
||||
let mut buf = [0; BUFSIZE];
|
||||
loop {
|
||||
@@ -36,6 +43,10 @@ fn read_from_tab_pty(sender: Box<PtyEventSender>, tab_id: TabId, mut reader: Box
|
||||
return;
|
||||
}
|
||||
Ok(size) => {
|
||||
spawner.spawn(Box::new(futures::future::lazy(|| {
|
||||
eprintln!("I was spawned from a pty thread");
|
||||
futures::future::ok(())
|
||||
})));
|
||||
if sender
|
||||
.send(PtyEvent::Data {
|
||||
tab_id,
|
||||
@@ -88,6 +99,10 @@ impl<'a> TerminalHost for Host<'a> {
|
||||
}
|
||||
|
||||
impl Mux {
|
||||
pub fn set_spawner(&self, spawner: Spawner) {
|
||||
*self.spawner.borrow_mut() = Some(spawner);
|
||||
}
|
||||
|
||||
pub fn get_tab(&self, tab_id: TabId) -> Option<Rc<Tab>> {
|
||||
self.tabs.borrow().get(&tab_id).map(Rc::clone)
|
||||
}
|
||||
@@ -97,7 +112,8 @@ impl Mux {
|
||||
|
||||
let reader = tab.reader()?;
|
||||
let tab_id = tab.tab_id();
|
||||
thread::spawn(move || read_from_tab_pty(sender, tab_id, reader));
|
||||
let spawner = self.spawner.borrow().as_ref().unwrap().clone();
|
||||
thread::spawn(move || read_from_tab_pty(spawner, sender, tab_id, reader));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user