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 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
#![deny(unsafe_code)]
use core::{
clone::Clone,
fmt::{Debug, Formatter},
marker::PhantomData,
sync::atomic::{AtomicBool, AtomicUsize, Ordering},
};
use std::{
borrow::Cow,
sync::{Arc, Condvar, Mutex},
thread,
};
const ZER: usize = 0;
const TRU: bool = true;
const FAL: bool = false;
/// Result for Futurized task,
///
/// where C: type of ITaskHandle sync sender value, T: type of Completed value,
pub enum Progress<'a, C, T> {
/// Current progress of the task
Current(Option<C>),
/// Indicates if the task is canceled
Canceled,
Completed(T),
Error(Cow<'a, str>),
}
impl<'a, C: Debug, T: Debug> Debug for Progress<'a, C, T> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
Self::Current(val) => write!(f, "Current: {:?}", val),
Self::Canceled => write!(f, "Canceled"),
Self::Completed(val) => write!(f, "Completed: {:?}", val),
Self::Error(val) => write!(f, "Error: {}", val),
}
}
}
impl<'a, C: Clone, T: Clone> Clone for Progress<'a, C, T> {
fn clone(&self) -> Self {
match self {
Self::Current(val) => Self::Current(Clone::clone(val)),
Self::Canceled => Self::Canceled,
Self::Completed(val) => Self::Completed(Clone::clone(val)),
Self::Error(val) => Self::Error(Clone::clone(val)),
}
}
}
/// Runtime handle of the task.
pub struct RuntimeHandle {
_id: usize,
rt_states: Arc<(AtomicBool, AtomicBool, AtomicBool, AtomicBool)>,
}
impl Clone for RuntimeHandle {
fn clone(&self) -> Self {
let _self = self;
Self {
_id: _self._id,
rt_states: Arc::clone(&_self.rt_states),
}
}
}
impl RuntimeHandle {
/// Get the id of the task
pub fn id(&self) -> usize {
self._id
}
/// Send signal to the inner task handle that the task should be suspended,
///
/// this won't do anything if not explicitly configured inside the task.
pub fn suspend(&self) {
self.rt_states.3.store(TRU, Ordering::Relaxed)
}
/// Resume the suspended task.
pub fn resume(&self) {
self.rt_states.3.store(FAL, Ordering::Relaxed)
}
/// Check if progress of the task is resumed.
pub fn is_resumed(&self) -> bool {
!self.rt_states.3.load(Ordering::Relaxed)
}
/// Check if progress of the task is suspended.
pub fn is_suspended(&self) -> bool {
self.rt_states.3.load(Ordering::Relaxed)
}
/// Send signal to the inner task handle that the task should be canceled.
///
/// this won't do anything if not explicitly configured inside the task.
pub fn cancel(&self) {
self.rt_states.2.store(TRU, Ordering::Relaxed)
}
/// Check if progress of the task is canceled.
pub fn is_canceled(&self) -> bool {
self.rt_states.2.load(Ordering::Relaxed)
}
/// Check if the task is in progress.
pub fn is_in_progress(&self) -> bool {
self.rt_states.0.load(Ordering::Relaxed)
}
/// Check if the task isn't in progress anymore (done).
pub fn is_done(&self) -> bool {
!self.rt_states.0.load(Ordering::Relaxed)
}
}
/// Inner handle of the task,
///
/// where C: type of sync sender value.
pub struct ITaskHandle<C> {
_id: usize,
rt_states: Arc<(AtomicBool, AtomicBool, AtomicBool, AtomicBool)>,
sync_s: Arc<(AtomicBool, Mutex<Option<C>>, Condvar)>,
}
impl<C> Clone for ITaskHandle<C> {
fn clone(&self) -> Self {
let _self = self;
Self {
_id: _self._id,
rt_states: Arc::clone(&_self.rt_states),
sync_s: Arc::clone(&_self.sync_s),
}
}
}
impl<C: Clone + Send + 'static> ITaskHandle<C> {
/// Send current progress of the task.
///
pub fn send(&self, t: C) {
let (ready, mtx, cvar) = &*self.sync_s;
if let Ok(mut mtx) = mtx.lock() {
*mtx = Some(t);
ready.store(TRU, Ordering::Relaxed);
let _ = cvar.wait(mtx);
}
}
/// Get the id of the task
pub fn id(&self) -> usize {
self._id
}
/// Check if progress of the task should be suspended,
///
/// usually applied for a specific task with event loop in it.
///
/// do other things (switch) while the task is suspended.
pub fn should_suspend(&self) -> bool {
self.rt_states.3.load(Ordering::Relaxed)
}
/// Check if progress of the task should be canceled.
pub fn should_cancel(&self) -> bool {
self.rt_states.2.load(Ordering::Relaxed)
}
}
impl<C> Drop for ITaskHandle<C> {
fn drop(&mut self) {
if thread::panicking() {
self.rt_states.1.store(TRU, Ordering::Relaxed)
}
}
}
/// Type name of ITaskHandle,
///
/// Use this if there's no needed for sending current value through channel and if type of ITaskHandle sync sender value not necessary to be known.
pub type InnerTaskHandle = ITaskHandle<()>;
/// Handle of the task.
pub struct TaskHandle<C, T> {
_id: usize,
states: Arc<(
Box<dyn Send + Sync + Fn(ITaskHandle<C>) -> Progress<'static, C, T>>,
Mutex<Progress<'static, C, T>>,
AtomicBool,
AtomicUsize,
)>,
rt_states: Arc<(AtomicBool, AtomicBool, AtomicBool, AtomicBool)>,
sync_s: Arc<(AtomicBool, Mutex<Option<C>>, Condvar)>,
}
impl<C, T> Clone for TaskHandle<C, T> {
fn clone(&self) -> Self {
let _self = self;
Self {
_id: _self._id,
states: Arc::clone(&_self.states),
rt_states: Arc::clone(&_self.rt_states),
sync_s: Arc::clone(&_self.sync_s),
}
}
}
impl<C, T> TaskHandle<C, T>
where
C: Clone + Send + 'static,
T: Clone + Send + 'static,
{
/// Get the id of the task
pub fn id(&self) -> usize {
self._id
}
/// Set stack size (in bytes) of the thread for spawning Futurized task,
///
/// Rust's official doc: https://doc.rust-lang.org/std/thread/struct.Builder.html#method.stack_size
///
/// if the given value is zero or default, it will use Rust's standard stack size.
pub fn stack_size(&self, size: usize) {
self.states.3.store(size, Ordering::Relaxed)
}
/// Try (it won't block the current thread) to do the task now,
///
/// and then try to resolve later.
pub fn try_do(&self) {
let waiting = &self.rt_states.0;
if !waiting.load(Ordering::SeqCst) {
waiting.store(TRU, Ordering::SeqCst);
let _self = self;
_self.rt_states.2.store(FAL, Ordering::Relaxed);
let _stack_size = _self.states.3.load(Ordering::Relaxed);
let states = Arc::clone(&_self.states);
let inner_task_handle = ITaskHandle {
_id: _self._id,
rt_states: Arc::clone(&_self.rt_states),
sync_s: Arc::clone(&_self.sync_s),
};
let task = move || {
let (closure, mtx, ready, _) = &*states;
let result = closure(inner_task_handle);
if let Ok(mut mtx) = mtx.lock() {
*mtx = result;
}
ready.store(TRU, Ordering::Relaxed)
};
if _stack_size == ZER {
thread::spawn(task);
} else {
// Should panic if the given stack size value is incorrect, so it's better to unwrap() here.
thread::Builder::new()
.stack_size(_stack_size)
.spawn(task)
.unwrap();
}
}
}
/// Send signal to the inner task handle that the task should be suspended.
///
/// this won't do anything if not explicitly configured inside the task.
pub fn suspend(&self) {
self.rt_states.3.store(TRU, Ordering::Relaxed)
}
/// Resume the suspended task.
pub fn resume(&self) {
self.rt_states.3.store(FAL, Ordering::Relaxed)
}
/// Check if progress of the task is suspended.
pub fn is_suspended(&self) -> bool {
self.rt_states.3.load(Ordering::Relaxed)
}
/// Check if progress of the task is resumed.
pub fn is_resumed(&self) -> bool {
!self.rt_states.3.load(Ordering::Relaxed)
}
/// Send signal to the inner task handle that the task should be canceled.
///
/// this won't do anything if not explicitly configured inside the task.
pub fn cancel(&self) {
self.rt_states.2.store(TRU, Ordering::Relaxed)
}
/// Check if progress of the task is canceled.
pub fn is_canceled(&self) -> bool {
self.rt_states.2.load(Ordering::Relaxed)
}
/// Check if the task is in progress.
pub fn is_in_progress(&self) -> bool {
self.rt_states.0.load(Ordering::Relaxed)
}
/// Check if the task isn't in progress anymore (done).
pub fn is_done(&self) -> bool {
!self.rt_states.0.load(Ordering::Relaxed)
}
}
/// Futurize task asynchronously.
/// # Example:
///
///```
///use asynchron::{Futurize, Futurized, ITaskHandle, Progress};
///use std::{
/// io::Error,
/// time::{Duration, Instant},
///};
///
///fn main() {
/// let instant: Instant = Instant::now();
/// let task: Futurized<String, u32> = Futurize::task(
/// 0,
/// move |_task: ITaskHandle<String>| -> Progress<String, u32> {
/// // // Panic if need to.
/// // // will return Error with a message:
/// // // "the task with id: (specific task id) panicked!"
/// // std::panic::panic_any("loudness");
/// let sleep_dur = Duration::from_millis(10);
/// std::thread::sleep(sleep_dur);
/// let result = Ok::<String, Error>(
/// format!("The task with id: {} wake up from sleep", _task.id()).into(),
/// );
/// match result {
/// Ok(value) => {
/// // Send current task progress.
/// _task.send(value)
/// }
/// Err(e) => {
/// // Return error immediately if something not right, for example:
/// return Progress::Error(e.to_string().into());
/// }
/// }
///
/// if _task.should_cancel() {
/// _task.send("Canceling the task".into());
/// return Progress::Canceled;
/// }
/// Progress::Completed(instant.elapsed().subsec_millis())
/// },
/// );
///
/// // Try do the task now.
/// task.try_do();
///
/// let mut exit = false;
/// loop {
/// task.try_resolve(|progress, done| {
/// match progress {
/// Progress::Current(task_receiver) => {
/// if let Some(value) = task_receiver {
/// println!("{}\n", value)
/// }
/// // // Cancel if need to.
/// // task.cancel()
/// }
/// Progress::Canceled => {
/// println!("The task was canceled\n")
/// }
/// Progress::Completed(elapsed) => {
/// println!("The task finished in: {:?} milliseconds\n", elapsed)
/// }
/// Progress::Error(e) => {
/// println!("{}\n", e)
/// }
/// }
///
/// if done {
/// // This scope act like "finally block", do final things here.
/// exit = true
/// }
/// });
///
/// if exit {
/// break;
/// }
/// }
///}
///```
pub struct Futurize<C, T> {
_data: PhantomData<(C, T)>,
}
impl<C: Clone + Send + 'static, T> Futurize<C, T> {
/// Create new task.
pub fn task<F>(id: usize, f: F) -> Futurized<C, T>
where
F: Send + Sync + Fn(ITaskHandle<C>) -> Progress<'static, C, T> + 'static,
{
Futurized {
_id: id,
states: Arc::new((
Box::new(f),
Mutex::new(Progress::Current(None)),
AtomicBool::new(FAL),
AtomicUsize::new(ZER),
)),
receiver: Arc::new((AtomicBool::new(FAL), Mutex::new(None), Condvar::new())),
rt_states: Arc::new((
AtomicBool::new(FAL),
AtomicBool::new(FAL),
AtomicBool::new(FAL),
AtomicBool::new(FAL),
)),
}
}
}
/// Futurized task.
pub struct Futurized<C, T> {
_id: usize,
states: Arc<(
Box<dyn Send + Sync + Fn(ITaskHandle<C>) -> Progress<'static, C, T>>,
Mutex<Progress<'static, C, T>>,
AtomicBool,
AtomicUsize,
)>,
receiver: Arc<(AtomicBool, Mutex<Option<C>>, Condvar)>,
rt_states: Arc<(AtomicBool, AtomicBool, AtomicBool, AtomicBool)>,
}
impl<C, T> Clone for Futurized<C, T> {
fn clone(&self) -> Self {
let _self = self;
Self {
_id: _self._id,
states: Arc::clone(&_self.states),
receiver: Arc::clone(&_self.receiver),
rt_states: Arc::clone(&_self.rt_states),
}
}
}
impl<C, T> Futurized<C, T>
where
C: Clone + Send + 'static,
T: Clone + Send + 'static,
{
/// Set stack size (in bytes) of the thread for spawning Futurized task,
///
/// Rust's official doc: https://doc.rust-lang.org/std/thread/struct.Builder.html#method.stack_size
///
/// if the given value is zero or default, it will use Rust's standard stack size.
pub fn stack_size(&self, size: usize) {
self.states.3.store(size, Ordering::Relaxed)
}
/// Try (it won't block the current thread) to do the task now,
///
/// and then try to resolve later.
pub fn try_do(&self) {
let waiting = &self.rt_states.0;
if !waiting.load(Ordering::SeqCst) {
waiting.store(TRU, Ordering::SeqCst);
let _self = self;
_self.rt_states.2.store(FAL, Ordering::Relaxed);
let _stack_size = _self.states.3.load(Ordering::Relaxed);
let states = Arc::clone(&_self.states);
let inner_task_handle = ITaskHandle {
_id: _self._id,
rt_states: Arc::clone(&_self.rt_states),
sync_s: Arc::clone(&_self.receiver),
};
let task = move || {
let (closure, mtx, ready, _) = &*states;
let result = closure(inner_task_handle);
if let Ok(mut mtx) = mtx.lock() {
*mtx = result;
}
ready.store(TRU, Ordering::Relaxed)
};
if _stack_size == ZER {
thread::spawn(task);
} else {
// Should panic if the given stack size value is incorrect, so it's better to unwrap() here.
thread::Builder::new()
.stack_size(_stack_size)
.spawn(task)
.unwrap();
}
}
}
/// Send signal to the inner task handle that the task should be suspended.
///
/// this won't do anything if not explicitly configured inside the task.
pub fn suspend(&self) {
self.rt_states.3.store(TRU, Ordering::Relaxed)
}
/// Resume the suspended task.
pub fn resume(&self) {
self.rt_states.3.store(FAL, Ordering::Relaxed)
}
/// Check if progress of the task is suspended.
pub fn is_suspended(&self) -> bool {
self.rt_states.3.load(Ordering::Relaxed)
}
/// Check if progress of the task is resumed.
pub fn is_resumed(&self) -> bool {
!self.rt_states.3.load(Ordering::Relaxed)
}
/// Send signal to the inner task handle that the task should be canceled.
///
/// this won't do anything if not explicitly configured inside the task.
pub fn cancel(&self) {
self.rt_states.2.store(TRU, Ordering::Relaxed)
}
/// Check if progress of the task is canceled.
pub fn is_canceled(&self) -> bool {
self.rt_states.2.load(Ordering::Relaxed)
}
/// Get the task handle, if only intended to try to do,
///
/// check progress, cancel, suspend or resume the task, from inside moving closures,
///
/// or from other threads to avoid (channel) synchronous Sender data races.
pub fn handle(&self) -> TaskHandle<C, T> {
let _self = self;
TaskHandle {
_id: _self._id,
states: Arc::clone(&_self.states),
sync_s: Arc::clone(&_self.receiver),
rt_states: Arc::clone(&_self.rt_states),
}
}
/// Get the runtime handle, if only intended to check progress, cancel,
///
/// suspend or resume the task from inside moving closures or from other threads.
///
/// use this to avoid unnecessary cloning unused task values.
pub fn rt_handle(&self) -> RuntimeHandle {
let _self = self;
RuntimeHandle {
_id: _self._id,
rt_states: Arc::clone(&_self.rt_states),
}
}
/// Get the id of the task
pub fn id(&self) -> usize {
self._id
}
/// Try resolve the progress of the task,
///
/// WARNING! to prevent from data races this fn should be called once at a time.
pub fn try_resolve<F: FnOnce(Progress<C, T>, bool) -> ()>(&self, f: F) {
if self.rt_states.0.load(Ordering::Relaxed) {
let mut done = false;
let mut result = || {
let _self = self;
let (awaiting, task_panicked, _, suspended) = &*_self.rt_states;
{
if task_panicked.load(Ordering::Relaxed) {
suspended.store(FAL, Ordering::Relaxed);
task_panicked.store(FAL, Ordering::Relaxed);
// fixes unsound problem, return error immediately if the task is panicked.
done = true;
return Progress::Error(Cow::Owned(format!(
"the task with id: {} panicked!",
_self._id
)));
}
}
if awaiting.load(Ordering::Relaxed) {
let _self = _self;
{
if _self.receiver.0.load(Ordering::Relaxed) {
let (ready, mtx, cvar) = &*_self.receiver;
let result = if let Ok(mut mtx) = mtx.lock() {
let result = Clone::clone(&*mtx);
*mtx = None;
result
} else {
None
};
ready.store(FAL, Ordering::Relaxed);
cvar.notify_all();
return Progress::Current(result);
}
}
let ready = &_self.states.2;
if ready.load(Ordering::Relaxed) {
suspended.store(FAL, Ordering::Relaxed);
let mtx = &_self.states.1;
// there's almost zero chance to deadlock,
// already guarded + with 2 atomicbools (awaiting and ready), so it's safe to unwrap here.
let mut mtx = mtx.lock().unwrap();
let result = Clone::clone(&*mtx);
*mtx = Progress::Current(None);
ready.store(FAL, Ordering::Relaxed);
done = true;
return result;
}
return Progress::Current(None);
}
Progress::Current(None)
};
f(result(), done);
if done {
self.rt_states.0.store(FAL, Ordering::Relaxed);
}
}
}
/// Check if the task is in progress.
pub fn is_in_progress(&self) -> bool {
self.rt_states.0.load(Ordering::Relaxed)
}
/// Check if the task isn't in progress anymore (done).
pub fn is_done(&self) -> bool {
!self.rt_states.0.load(Ordering::Relaxed)
}
}
/// Tricky oneshot thread safe state management
///
/// WARNING!
/// (if not sure how to use it, don't use it)
///
/// using std::sync::Arc, std::sync::Mutex and core::option::Option under the hood.
///
/// # Example:
///
///```
///use asynchron::SyncState;
///
///fn main() -> core::result::Result<(), Box<dyn std::error::Error>> {
/// let state: SyncState<i32> = SyncState::new(0);
/// let _state = state.clone();
///
/// // The state will be empty if it successfully loaded.
/// match state.load() {
/// Some(value) => {
/// println!("initial value: {:?}", value)
/// }
/// _ => (),
/// }
///
/// assert_eq!(true, state.is_empty());
///
/// if let Err(_) = std::thread::spawn(move || {
/// if _state.is_empty() {
/// // Restore the state.
/// _state.store(20)
/// }
/// })
/// .join()
/// {
/// let e = std::io::Error::new(std::io::ErrorKind::Other, "Unable to join the thread.");
/// return Err(Box::new(e));
/// }
///
/// if state.is_full() {
/// match state.load() {
/// Some(value) => {
/// assert_eq!(value, 20);
/// println!("latest value {:?}", value)
/// }
/// _ => {
/// let e = std::io::Error::new(std::io::ErrorKind::Other, "State not restore.");
/// return Err(Box::new(e));
/// }
/// }
/// }
///
/// assert_eq!(true, state.is_empty());
///
/// Ok(())
///}
///```
pub struct SyncState<T> {
item: Arc<(Mutex<Option<T>>, AtomicBool)>,
}
impl<T> Clone for SyncState<T> {
fn clone(&self) -> Self {
Self {
item: Arc::clone(&self.item),
}
}
}
impl<T: Clone + Send + ?Sized> SyncState<T> {
/// Create new state.
pub fn new(t: T) -> SyncState<T> {
SyncState {
item: Arc::new((Mutex::new(Some(t)), AtomicBool::new(FAL))),
}
}
/// Load new value from the state.
pub fn load(&self) -> Option<T> {
if let Ok(mut mtx) = self.item.0.lock() {
let result = Clone::clone(&*mtx);
*mtx = None;
self.item.1.store(TRU, Ordering::Relaxed);
return result;
}
None
}
/// Store new value to the state
pub fn store(&self, t: T) {
if let Ok(mut value) = self.item.0.lock() {
*value = Some(t);
self.item.1.store(FAL, Ordering::Relaxed)
}
}
/// Check if the state isn't full (if it isn't full, just store it).
pub fn is_empty(&self) -> bool {
self.item.1.load(Ordering::Relaxed)
}
/// Check if the state isn't empty (if it isn't empty, just load it).
pub fn is_full(&self) -> bool {
!self.item.1.load(Ordering::Relaxed)
}
}