mirror of https://git.meli.delivery/meli/meli
Replace old pseudo-async code with blocking rust async
parent
a190805384
commit
3eadaba34e
@ -1,255 +0,0 @@
|
||||
/*
|
||||
* meli - async module
|
||||
*
|
||||
* Copyright 2017 Manos Pitsidianakis
|
||||
*
|
||||
* This file is part of meli.
|
||||
*
|
||||
* meli is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* meli is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with meli. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/*!
|
||||
* Primitive Async/Wait implementation.
|
||||
*
|
||||
* To create an Async promise, create an AsyncBuilder. Ask for its channel receiver/sender with
|
||||
* `tx` and `rx` methods to pass them in your worker's closure. Build an `Async<T>` with your
|
||||
* `JoinHandle<T>`. The thread must communicate with the `Async<T>` object via `AsyncStatus`
|
||||
* messages.
|
||||
*
|
||||
* When `Async<T>` receives `AsyncStatus::Finished` it joins the thread and takes its value which
|
||||
* can be extracted with `extract`.
|
||||
*/
|
||||
|
||||
use crossbeam::{
|
||||
bounded,
|
||||
channel::{Receiver, Sender},
|
||||
select,
|
||||
};
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WorkContext {
|
||||
pub new_work: Sender<Work>,
|
||||
pub set_name: Sender<(std::thread::ThreadId, String)>,
|
||||
pub set_status: Sender<(std::thread::ThreadId, String)>,
|
||||
pub finished: Sender<std::thread::ThreadId>,
|
||||
}
|
||||
|
||||
pub struct Work {
|
||||
priority: u64,
|
||||
pub is_static: bool,
|
||||
pub closure: Box<dyn FnOnce(WorkContext) -> () + Send + Sync>,
|
||||
}
|
||||
|
||||
impl Ord for Work {
|
||||
fn cmp(&self, other: &Work) -> std::cmp::Ordering {
|
||||
self.priority.cmp(&other.priority)
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Work {
|
||||
fn partial_cmp(&self, other: &Work) -> Option<std::cmp::Ordering> {
|
||||
Some(self.priority.cmp(&other.priority))
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Work {
|
||||
fn eq(&self, other: &Work) -> bool {
|
||||
self.priority == other.priority
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Work {}
|
||||
|
||||
impl Work {
|
||||
pub fn compute(self, work_context: WorkContext) {
|
||||
(self.closure)(work_context);
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Work {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "Work object")
|
||||
}
|
||||
}
|
||||
|
||||
/// Messages to pass between `Async<T>` owner and its worker thread.
|
||||
#[derive(Clone)]
|
||||
pub enum AsyncStatus<T> {
|
||||
NoUpdate,
|
||||
Payload(T),
|
||||
Finished,
|
||||
///The number may hold whatever meaning the user chooses.
|
||||
ProgressReport(usize),
|
||||
}
|
||||
|
||||
impl<T> fmt::Debug for AsyncStatus<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
AsyncStatus::NoUpdate => write!(f, "AsyncStatus<T>::NoUpdate"),
|
||||
AsyncStatus::Payload(_) => write!(f, "AsyncStatus<T>::Payload(_)"),
|
||||
AsyncStatus::Finished => write!(f, "AsyncStatus<T>::Finished"),
|
||||
AsyncStatus::ProgressReport(u) => write!(f, "AsyncStatus<T>::ProgressReport({})", u),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A builder object for `Async<T>`
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AsyncBuilder<T: Send + Sync> {
|
||||
tx: Sender<AsyncStatus<T>>,
|
||||
rx: Receiver<AsyncStatus<T>>,
|
||||
priority: u64,
|
||||
is_static: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Async<T: Send + Sync> {
|
||||
work: Option<Work>,
|
||||
active: bool,
|
||||
tx: Sender<AsyncStatus<T>>,
|
||||
rx: Receiver<AsyncStatus<T>>,
|
||||
}
|
||||
|
||||
impl<T: Send + Sync> Default for AsyncBuilder<T> {
|
||||
fn default() -> Self {
|
||||
AsyncBuilder::<T>::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> AsyncBuilder<T>
|
||||
where
|
||||
T: Send + Sync,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
let (sender, receiver) = bounded(8 * ::std::mem::size_of::<AsyncStatus<T>>());
|
||||
AsyncBuilder {
|
||||
tx: sender,
|
||||
rx: receiver,
|
||||
priority: 0,
|
||||
is_static: false,
|
||||
}
|
||||
}
|
||||
/// Returns the sender object of the promise's channel.
|
||||
pub fn tx(&mut self) -> Sender<AsyncStatus<T>> {
|
||||
self.tx.clone()
|
||||
}
|
||||
/// Returns the receiver object of the promise's channel.
|
||||
pub fn rx(&mut self) -> Receiver<AsyncStatus<T>> {
|
||||
self.rx.clone()
|
||||
}
|
||||
|
||||
pub fn set_priority(&mut self, new_val: u64) -> &mut Self {
|
||||
self.priority = new_val;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn set_is_static(&mut self, new_val: bool) -> &mut Self {
|
||||
self.is_static = new_val;
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns an `Async<T>` object that contains a `Thread` join handle that returns a `T`
|
||||
pub fn build(self, work: Box<dyn FnOnce(WorkContext) -> () + Send + Sync>) -> Async<T> {
|
||||
Async {
|
||||
work: Some(Work {
|
||||
priority: self.priority,
|
||||
is_static: self.is_static,
|
||||
closure: work,
|
||||
}),
|
||||
tx: self.tx,
|
||||
rx: self.rx,
|
||||
active: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Async<T>
|
||||
where
|
||||
T: Send + Sync,
|
||||
{
|
||||
pub fn work(&mut self) -> Option<Work> {
|
||||
if !self.active {
|
||||
self.active = true;
|
||||
self.work.take()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
/// Returns the sender object of the promise's channel.
|
||||
pub fn tx(&mut self) -> Sender<AsyncStatus<T>> {
|
||||
self.tx.clone()
|
||||
}
|
||||
/// Returns the receiver object of the promise's channel.
|
||||
pub fn rx(&mut self) -> Receiver<AsyncStatus<T>> {
|
||||
self.rx.clone()
|
||||
}
|
||||
/// Polls worker thread and returns result.
|
||||
pub fn poll_block(&mut self) -> Result<AsyncStatus<T>, ()> {
|
||||
if !self.active {
|
||||
return Ok(AsyncStatus::Finished);
|
||||
}
|
||||
|
||||
let rx = &self.rx;
|
||||
select! {
|
||||
recv(rx) -> r => {
|
||||
match r {
|
||||
Ok(p @ AsyncStatus::Payload(_)) => {
|
||||
Ok(p)
|
||||
},
|
||||
Ok(f @ AsyncStatus::Finished) => {
|
||||
self.active = false;
|
||||
Ok(f)
|
||||
},
|
||||
Ok(a) => {
|
||||
Ok(a)
|
||||
}
|
||||
Err(_) => {
|
||||
Err(())
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
/// Polls worker thread and returns result.
|
||||
pub fn poll(&mut self) -> Result<AsyncStatus<T>, ()> {
|
||||
if !self.active {
|
||||
return Ok(AsyncStatus::Finished);
|
||||
}
|
||||
|
||||
let rx = &self.rx;
|
||||
select! {
|
||||
default => {
|
||||
Ok(AsyncStatus::NoUpdate)
|
||||
},
|
||||
recv(rx) -> r => {
|
||||
match r {
|
||||
Ok(p @ AsyncStatus::Payload(_)) => {
|
||||
Ok(p)
|
||||
},
|
||||
Ok(f @ AsyncStatus::Finished) => {
|
||||
self.active = false;
|
||||
Ok(f)
|
||||
},
|
||||
Ok(a) => {
|
||||
Ok(a)
|
||||
}
|
||||
Err(_) => {
|
||||
Err(())
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
@ -1,385 +0,0 @@
|
||||
/*
|
||||
* meli
|
||||
*
|
||||
* Copyright 2017-2020 Manos Pitsidianakis
|
||||
*
|
||||
* This file is part of meli.
|
||||
*
|
||||
* meli is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* meli is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with meli. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
/*! Simple blocking job control.
|
||||
*/
|
||||
use crate::types::ThreadEvent;
|
||||
use crossbeam::{
|
||||
channel::{bounded, unbounded, Sender},
|
||||
select,
|
||||
};
|
||||
use melib::async_workers::{Work, WorkContext};
|
||||
use melib::datetime::{self, UnixTimestamp};
|
||||
use melib::text_processing::Truncate;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::thread;
|
||||
|
||||
const MAX_WORKER: usize = 4;
|
||||
|
||||
/// Representation of a worker thread for use in `WorkController`. These values are to be displayed
|
||||
/// to the user.
|
||||
#[derive(Debug)]
|
||||
pub struct Worker {
|
||||
pub name: String,
|
||||
pub status: String,
|
||||
pub heartbeat: UnixTimestamp,
|
||||
}
|
||||
|
||||
impl From<String> for Worker {
|
||||
fn from(val: String) -> Self {
|
||||
Worker {
|
||||
name: val,
|
||||
status: String::new(),
|
||||
heartbeat: datetime::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WorkController {
|
||||
pub queue: WorkQueue,
|
||||
thread_end_tx: Sender<bool>,
|
||||
/// Worker threads that take up on jobs from self.queue
|
||||
pub threads: Arc<Mutex<HashMap<thread::ThreadId, Worker>>>,
|
||||
/// Special function threads that live indefinitely (eg watching a mailbox)
|
||||
pub static_threads: Arc<Mutex<HashMap<thread::ThreadId, Worker>>>,
|
||||
work_context: WorkContext,
|
||||
}
|
||||
|
||||
impl Drop for WorkController {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(lock) = self.threads.lock() {
|
||||
for _ in 0..lock.len() {
|
||||
let _ = self.thread_end_tx.send(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct WorkQueue {
|
||||
inner: Arc<Mutex<Vec<Work>>>,
|
||||
new_jobs_tx: Sender<bool>,
|
||||
work_context: WorkContext,
|
||||
}
|
||||
|
||||
impl WorkQueue {
|
||||
fn new(new_jobs_tx: Sender<bool>, work_context: WorkContext) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(Mutex::new(Vec::new())),
|
||||
new_jobs_tx,
|
||||
work_context,
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocks the current thread until work is available, then
|
||||
/// gets the data required to perform that work.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns None if there is no more work in the queue.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if the underlying mutex became poisoned. This is exceedingly
|
||||
/// unlikely.
|
||||
fn get_work(&self) -> Option<Work> {
|
||||
// try to get a lock on the mutex.
|
||||
let maybe_queue = self.inner.lock();
|
||||
if let Ok(mut queue) = maybe_queue {
|
||||
if queue.is_empty() {
|
||||
return None;
|
||||
} else {
|
||||
return Some(queue.swap_remove(0));
|
||||
}
|
||||
} else {
|
||||
// poisoned mutex, some other thread holding the mutex has panicked!
|
||||
panic!("WorkQueue::get_work() tried to lock a poisoned mutex");
|
||||
}
|
||||
}
|
||||
|
||||
// Both the controller (main thread) and workers can use this
|
||||
// function to add work to the queue.
|
||||
|
||||
/// Blocks the current thread until work can be added, then
|
||||
/// adds that work to the end of the queue.
|
||||
/// Returns the amount of work now in the queue.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if the underlying mutex became poisoned. This is exceedingly
|
||||
/// unlikely.
|
||||
pub fn add_work(&self, work: Work) {
|
||||
if work.is_static {
|
||||
self.work_context.new_work.send(work).unwrap();
|
||||
return;
|
||||
}
|
||||
|
||||
// As above, try to get a lock on the mutex.
|
||||
if let Ok(mut queue) = self.inner.lock() {
|
||||
/* Insert in position that maintains the queue sorted */
|
||||
let pos = match queue.binary_search_by(|probe| probe.cmp(&work)) {
|
||||
Ok(p) => p,
|
||||
Err(p) => p,
|
||||
};
|
||||
queue.insert(pos, work);
|
||||
|
||||
/* inform threads that new job is available */
|
||||
self.new_jobs_tx.send(true).unwrap();
|
||||
} else {
|
||||
panic!("WorkQueue::add_work() tried to lock a poisoned mutex");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WorkController {
|
||||
pub fn new(pulse: Sender<ThreadEvent>) -> WorkController {
|
||||
let (new_jobs_tx, new_jobs_rx) = unbounded();
|
||||
|
||||
/* create a channel for jobs to send new work to Controller thread */
|
||||
let (new_work_tx, new_work_rx) = unbounded();
|
||||
|
||||
/* create a channel for jobs to set their names */
|
||||
let (set_name_tx, set_name_rx) = unbounded();
|
||||
|
||||
/* create a channel for jobs to set their statuses */
|
||||
let (set_status_tx, set_status_rx) = unbounded();
|
||||
|
||||
/* create a channel for jobs to announce their demise */
|
||||
let (finished_tx, finished_rx) = unbounded();
|
||||
|
||||
/* each associated thread will hold a copy of this context item in order to communicate
|
||||
* with the controller thread */
|
||||
let work_context = WorkContext {
|
||||
new_work: new_work_tx,
|
||||
set_name: set_name_tx,
|
||||
set_status: set_status_tx,
|
||||
finished: finished_tx,
|
||||
};
|
||||
|
||||
let queue: WorkQueue = WorkQueue::new(new_jobs_tx, work_context.clone());
|
||||
|
||||
let active_threads = Arc::new(AtomicUsize::new(MAX_WORKER));
|
||||
// Create a SyncFlag to share whether or not there are more jobs to be done.
|
||||
let (thread_end_tx, thread_end_rx) = bounded(1);
|
||||
|
||||
let threads_lock: Arc<Mutex<HashMap<thread::ThreadId, Worker>>> =
|
||||
Arc::new(Mutex::new(HashMap::default()));
|
||||
|
||||
let static_threads_lock: Arc<Mutex<HashMap<thread::ThreadId, Worker>>> =
|
||||
Arc::new(Mutex::new(HashMap::default()));
|
||||
|
||||
let mut threads = threads_lock.lock().unwrap();
|
||||
/* spawn worker threads */
|
||||
for _ in 0..MAX_WORKER {
|
||||
/* Each worker thread will wait on two channels: thread_end and new_jobs. thread_end
|
||||
* informs the worker that it should quit and new_jobs informs that there is a new job
|
||||
* available inside the queue. Only one worker will get each job, and others will
|
||||
* go back to waiting on the channels */
|
||||
let thread_queue = queue.clone();
|
||||
|
||||
let active_threads = active_threads.clone();
|
||||
let thread_end_rx = thread_end_rx.clone();
|
||||
let new_jobs_rx = new_jobs_rx.clone();
|
||||
let new_jobs_rx = new_jobs_rx.clone();
|
||||
|
||||
let work_context = work_context.clone();
|
||||
let pulse = pulse.clone();
|
||||
|
||||
let handle = spawn_worker(
|
||||
thread_queue,
|
||||
active_threads,
|
||||
thread_end_rx,
|
||||
new_jobs_rx,
|
||||
work_context,
|
||||
pulse,
|
||||
);
|
||||
|
||||
/* add the handle for the newly spawned thread to the list of handles */
|
||||
threads.insert(handle.thread().id(), String::from("idle-worker").into());
|
||||
}
|
||||
/* drop lock */
|
||||
drop(threads);
|
||||
|
||||
{
|
||||
/* start controller thread */
|
||||
let threads_lock = threads_lock.clone();
|
||||
let _static_threads_lock = static_threads_lock.clone();
|
||||
let thread_queue = queue.clone();
|
||||
let thread_end_rx = thread_end_rx.clone();
|
||||
let work_context = work_context.clone();
|
||||
|
||||
let handle = thread::spawn(move || 'control_loop: loop {
|
||||
select! {
|
||||
recv(thread_end_rx) -> _ => {
|
||||
debug!("received thread_end_rx, quitting");
|
||||
break 'control_loop;
|
||||
},
|
||||
recv(new_work_rx) -> work => {
|
||||
if let Ok(work) = work {
|
||||
if work.is_static {
|
||||
let work_context = work_context.clone();
|
||||
let handle = thread::spawn(move || work.compute(work_context));
|
||||
_static_threads_lock.lock().unwrap().insert(handle.thread().id(), String::new().into());
|
||||
} else {
|
||||
if active_threads.load(Ordering::SeqCst) == 0 {
|
||||
let handle = spawn_worker(
|
||||
thread_queue.clone(),
|
||||
active_threads.clone(),
|
||||
thread_end_rx.clone(),
|
||||
new_jobs_rx.clone(),
|
||||
work_context.clone(),
|
||||
pulse.clone(),
|
||||
);
|
||||
|
||||
/* add the handle for the newly spawned thread to the list of handles */
|
||||
threads_lock.lock().unwrap().insert(handle.thread().id(), String::from("idle-worker").into());
|
||||
}
|
||||
thread_queue.add_work(work);
|
||||
}
|
||||
}
|
||||
}
|
||||
recv(set_name_rx) -> new_name => {
|
||||
if let Ok((thread_id, mut new_name)) = new_name {
|
||||
new_name.truncate_at_boundary(256);
|
||||
let mut threads = threads_lock.lock().unwrap();
|
||||
let mut static_threads = _static_threads_lock.lock().unwrap();
|
||||
let now = datetime::now();
|
||||
if threads.contains_key(&thread_id) {
|
||||
threads.entry(thread_id).and_modify(|e| {
|
||||
e.name = new_name;
|
||||
e.heartbeat = now;
|
||||
});
|
||||
} else if static_threads.contains_key(&thread_id) {
|
||||
static_threads.entry(thread_id).and_modify(|e| {
|
||||
|
||||
e.name = new_name;
|
||||
e.heartbeat = now;
|
||||
});
|
||||
} else {
|
||||
static_threads.insert(thread_id, Worker { heartbeat: now, .. new_name.into() });
|
||||
static_threads.entry(thread_id).and_modify(|e| {
|
||||
e.heartbeat = now;
|
||||
});
|
||||
}
|
||||
pulse.send(ThreadEvent::Pulse).unwrap();
|
||||
}
|
||||
}
|
||||
recv(set_status_rx) -> new_status => {
|
||||
if let Ok((thread_id, mut new_status)) = new_status {
|
||||
new_status.truncate_at_boundary(256);
|
||||
let mut threads = threads_lock.lock().unwrap();
|
||||
let mut static_threads = _static_threads_lock.lock().unwrap();
|
||||
let now = datetime::now();
|
||||
if threads.contains_key(&thread_id) {
|
||||
threads.entry(thread_id).and_modify(|e| {
|
||||
e.status = new_status;
|
||||
e.heartbeat = now;
|
||||
});
|
||||
} else if static_threads.contains_key(&thread_id) {
|
||||
static_threads.entry(thread_id).and_modify(|e| {
|
||||
e.status = new_status;
|
||||
e.heartbeat = now;
|
||||
});
|
||||
debug!(&static_threads[&thread_id]);
|
||||
} else {
|
||||
static_threads.insert(thread_id, Worker { status: new_status, heartbeat: now, .. String::new().into() });
|
||||
}
|
||||
pulse.send(ThreadEvent::Pulse).unwrap();
|
||||
}
|
||||
}
|
||||
recv(finished_rx) -> dead_thread_id => {
|
||||
if let Ok(thread_id) = dead_thread_id {
|
||||
let mut threads = threads_lock.lock().unwrap();
|
||||
let mut static_threads = _static_threads_lock.lock().unwrap();
|
||||
if threads.contains_key(&thread_id) {
|
||||
threads.remove(&thread_id);
|
||||
} else if static_threads.contains_key(&thread_id) {
|
||||
static_threads.remove(&thread_id);
|
||||
} else {
|
||||
/* Nothing to do */
|
||||
}
|
||||
pulse.send(ThreadEvent::Pulse).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let mut static_threads = static_threads_lock.lock().unwrap();
|
||||
static_threads.insert(
|
||||
handle.thread().id(),
|
||||
"WorkController-thread".to_string().into(),
|
||||
);
|
||||
}
|
||||
|
||||
WorkController {
|
||||
queue,
|
||||
thread_end_tx,
|
||||
threads: threads_lock,
|
||||
static_threads: static_threads_lock,
|
||||
work_context,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_static_thread(&mut self, id: std::thread::ThreadId) {
|
||||
self.static_threads
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id, String::new().into());
|
||||
}
|
||||
|
||||
pub fn get_context(&self) -> WorkContext {
|
||||
self.work_context.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_worker(
|
||||
thread_queue: WorkQueue,
|
||||
active_threads: Arc<AtomicUsize>,
|
||||
thread_end_rx: crossbeam::Receiver<bool>,
|
||||
new_jobs_rx: crossbeam::Receiver<bool>,
|
||||
work_context: WorkContext,
|
||||
pulse: crossbeam::Sender<ThreadEvent>,
|
||||
) -> std::thread::JoinHandle<()> {
|
||||
thread::spawn(move || 'work_loop: loop {
|
||||
debug!("Waiting for work");
|
||||
select! {
|
||||
recv(thread_end_rx) -> _ => {
|
||||
debug!("received thread_end_rx, quitting");
|
||||
active_threads.fetch_sub(1, Ordering::SeqCst);
|
||||
break 'work_loop;
|
||||
},
|
||||
recv(new_jobs_rx) -> _ => {
|
||||
active_threads.fetch_sub(1, Ordering::SeqCst);
|
||||
while let Some(work) = thread_queue.get_work() {
|
||||
debug!("Got some work");
|
||||
work.compute(work_context.clone());
|
||||
debug!("finished work");
|
||||
work_context.set_name.send((std::thread::current().id(), "idle-worker".to_string())).unwrap();
|
||||
work_context.set_status.send((std::thread::current().id(), "inactive".to_string())).unwrap();
|
||||
pulse.send(ThreadEvent::Pulse).unwrap();
|
||||
|
||||
std::thread::yield_now();
|
||||
}
|
||||
active_threads.fetch_add(1, Ordering::SeqCst);
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue