├── .gitignore ├── Cargo.toml ├── .github └── workflows │ └── ci.yml ├── examples ├── fltk_parallel_plotters │ ├── Cargo.toml │ └── src │ │ └── main.rs ├── fltk_fetch_ureq │ ├── Cargo.toml │ └── src │ │ └── main.rs ├── fltk_fetch_reqwest │ ├── Cargo.toml │ └── src │ │ └── main.rs └── vectored_tasks.rs ├── tests └── drive.rs ├── README.md ├── LICENSE └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "asynchron" 3 | version = "0.9.1" 4 | authors = ["Ar37-rs "] 5 | edition = "2018" 6 | description = "Asynchronize blocking operation." 7 | documentation = "https://docs.rs/asynchron" 8 | readme = "README.md" 9 | keywords = ["async", "sync", "std", "multi-thread", "non-blocking"] 10 | license = "MIT OR Apache-2.0" 11 | repository = "https://github.com/Ar37-rs/asynchron" 12 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 13 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ${{ matrix.os }} 16 | strategy: 17 | matrix: 18 | os: [windows-latest, macos-latest, ubuntu-latest] 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | - name: Build 23 | run: cargo build --verbose 24 | - name: Run tests 25 | run: cargo test --verbose 26 | -------------------------------------------------------------------------------- /examples/fltk_parallel_plotters/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "fltk_parallel_plotters" 3 | version = "0.9.1" 4 | authors = ["Ar37-rs "] 5 | edition = "2018" 6 | publish = false 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | # With fltk-bundled (faster build time) features work on windows, linux and mac x64 only (requires curl and tar) 11 | # fltk = { version = "1", features = ["fltk-bundled"] } 12 | fltk = "1" 13 | plotters = "0.3" 14 | plotters-bitmap = "0.3" 15 | asynchron = "0.9" -------------------------------------------------------------------------------- /examples/fltk_fetch_ureq/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "fltk_fetch_reqwest" 3 | version = "0.9.1" 4 | authors = ["Ar37-rs "] 5 | edition = "2018" 6 | publish = false 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | asynchron = "0.9" 11 | # asynchron = { path = "../../../asynchron" } 12 | # With fltk-bundled (faster build time) features work on windows, linux and mac x64 only (requires curl and tar) 13 | # fltk = { version = "1", features = ["fltk-bundled"] } 14 | fltk = "1" 15 | ureq = "2" 16 | -------------------------------------------------------------------------------- /examples/fltk_fetch_reqwest/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "fltk_fetch_reqwest" 3 | version = "0.9.1" 4 | authors = ["Ar37-rs "] 5 | edition = "2018" 6 | publish = false 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | asynchron = "0.9" 11 | # asynchron = { path = "../../../asynchron" } 12 | # With fltk-bundled (faster build time) features work on windows, linux and mac x64 only (requires curl and tar) 13 | # fltk = { version = "1", features = ["fltk-bundled"] } 14 | fltk = "1" 15 | reqwest = "0.11" 16 | tokio = { version = "1", features = ["rt-multi-thread"] } 17 | -------------------------------------------------------------------------------- /tests/drive.rs: -------------------------------------------------------------------------------- 1 | use asynchron::{Futurize, Futurized, ITaskHandle, Progress}; 2 | use std::io::Result; 3 | 4 | #[test] 5 | fn drive() -> Result<()> { 6 | let task: Futurized = 7 | Futurize::task(0, move |_task: ITaskHandle| -> Progress<_, i32> { 8 | for i in 0..5 { 9 | _task.send(i) 10 | } 11 | let mut counter = 0; 12 | counter += 1; 13 | Progress::Completed(counter) 14 | }); 15 | task.try_do(); 16 | let mut sum = 0; 17 | let mut exit = false; 18 | loop { 19 | task.try_resolve(|progress, done| { 20 | match progress { 21 | Progress::Current(receiver) => { 22 | if let Some(val) = receiver { 23 | sum += val; 24 | } 25 | } 26 | Progress::Completed(counter) => { 27 | println!("\ncounter value: {}", counter); 28 | assert_eq!(counter, 1); 29 | } 30 | _ => (), 31 | } 32 | 33 | if done { 34 | println!("sum value: {}\n", sum); 35 | assert_eq!(sum, 10); 36 | exit = true 37 | } 38 | }); 39 | 40 | if exit { 41 | break; 42 | } 43 | } 44 | Ok(()) 45 | } 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This repository has been archived use [Flowync](https://github.com/Ar37-rs/flowync) instead. 2 | 3 | # Asynchron 4 | [![Crates.io](https://img.shields.io/crates/v/asynchron.svg)](https://crates.io/crates/asynchron) 5 | [![Asynchron documentation](https://docs.rs/asynchron/badge.svg)](https://docs.rs/asynchron) 6 | [![CI](https://github.com/Ar37-rs/asynchron/actions/workflows/ci.yml/badge.svg)](https://github.com/Ar37-rs/asynchron/actions/workflows/ci.yml) 7 | 8 | Asynchronize blocking operation. 9 | 10 | ## Example 11 | 12 | ```rust 13 | use asynchron::{Futurize, Futurized, ITaskHandle, Progress}; 14 | use std::{ 15 | io::Error, 16 | time::{Duration, Instant}, 17 | }; 18 | 19 | fn main() { 20 | let instant: Instant = Instant::now(); 21 | let task: Futurized = Futurize::task( 22 | 0, 23 | move |_task: ITaskHandle| -> Progress { 24 | // // Panic if need to. 25 | // // will return Error with a message: 26 | // // "the task with id: (specific task id) panicked!" 27 | // std::panic::panic_any("loudness"); 28 | let sleep_dur = Duration::from_millis(10); 29 | std::thread::sleep(sleep_dur); 30 | let result = Ok::( 31 | format!("The task with id: {} wake up from sleep", _task.id()).into(), 32 | ); 33 | match result { 34 | Ok(value) => { 35 | // Send current task progress. 36 | _task.send(value) 37 | } 38 | Err(e) => { 39 | // Return error immediately if something not right, for example: 40 | return Progress::Error(e.to_string().into()); 41 | } 42 | } 43 | 44 | if _task.should_cancel() { 45 | _task.send("Canceling the task".into()); 46 | return Progress::Canceled; 47 | } 48 | Progress::Completed(instant.elapsed().subsec_millis()) 49 | }, 50 | ); 51 | 52 | // Try do the task now. 53 | task.try_do(); 54 | 55 | let mut exit = false; 56 | loop { 57 | task.try_resolve(|progress, done| { 58 | match progress { 59 | Progress::Current(task_receiver) => { 60 | if let Some(value) = task_receiver { 61 | println!("{}\n", value) 62 | } 63 | // // Cancel if need to. 64 | // task.cancel() 65 | } 66 | Progress::Canceled => { 67 | println!("The task was canceled\n") 68 | } 69 | Progress::Completed(elapsed) => { 70 | println!("The task finished in: {:?} milliseconds\n", elapsed) 71 | } 72 | Progress::Error(e) => { 73 | println!("{}\n", e) 74 | } 75 | } 76 | 77 | if done { 78 | // This scope act like "finally block", do final things here. 79 | exit = true 80 | } 81 | }); 82 | 83 | if exit { 84 | break; 85 | } 86 | } 87 | } 88 | ``` 89 | 90 | ## More Examples 91 | 92 | Unblock blocking ureq or reqwest with fltk-rs can be found [here](https://github.com/Ar37-rs/asynchron/tree/main/examples). 93 | -------------------------------------------------------------------------------- /examples/vectored_tasks.rs: -------------------------------------------------------------------------------- 1 | use asynchron::{Futurize, Futurized, ITaskHandle, Progress}; 2 | use std::{ 3 | io::Error, 4 | time::{Duration, Instant}, 5 | }; 6 | 7 | fn main() { 8 | let instant: Instant = Instant::now(); 9 | let mut vec_opt_tasks = Vec::new(); 10 | for i in 0..5 { 11 | let task: Futurized = Futurize::task( 12 | i, 13 | move |this: ITaskHandle| -> Progress { 14 | // // Panic if need to. 15 | // // will return Error with a message: 16 | // // "the task with id: (specific task id) panicked!" 17 | // if this.id() == 3 { 18 | // std::panic::panic_any("loudness") 19 | // } 20 | let millis = this.id() + 1; 21 | let sleep_dur = Duration::from_millis((10 * millis) as u64); 22 | std::thread::sleep(sleep_dur); 23 | let result = Ok::( 24 | format!("The task with id: {} wake up from sleep", this.id()).into(), 25 | ); 26 | match result { 27 | Ok(value) => { 28 | // Send current task progress. 29 | this.send(value) 30 | } 31 | Err(e) => { 32 | // Return error immediately if something not right, for example: 33 | return Progress::Error(e.to_string().into()); 34 | } 35 | } 36 | 37 | if this.should_cancel() { 38 | let value = format!("Canceling the task with id: {}", this.id()); 39 | this.send(value); 40 | return Progress::Canceled; 41 | } 42 | Progress::Completed(instant.elapsed().subsec_millis()) 43 | }, 44 | ); 45 | // Try do the task now. 46 | task.try_do(); 47 | vec_opt_tasks.push(Some(task)) 48 | } 49 | 50 | let num_tasks = vec_opt_tasks.len(); 51 | let mut count_down = num_tasks; 52 | 53 | loop { 54 | for i in 0..num_tasks { 55 | if let Some(task) = &vec_opt_tasks[i] { 56 | task.try_resolve(|progress, _| match progress { 57 | Progress::Current(task_receiver) => { 58 | if let Some(value) = task_receiver { 59 | println!("{}\n", value) 60 | } 61 | // // Cancel if need to. 62 | // if (task.id() % 2 != 0) || (task.id() == 0) { 63 | // task.cancel() 64 | // } 65 | 66 | // terminate if need to. 67 | // // change the line above like so: "if let Some(task) = vec_opt_tasks[i].clone() {..." 68 | // // and then simply set some items of vec_opt_tasks to None. 69 | // if (task.id() % 2 != 0) || (task.id() == 0) { 70 | // vec_opt_tasks[i] = None; 71 | // count_down -= 1 72 | // } 73 | } 74 | Progress::Canceled => { 75 | println!("The task with id: {} was canceled\n", task.id()) 76 | } 77 | Progress::Completed(elapsed) => { 78 | println!( 79 | "The task with id: {} finished in: {:?} milliseconds\n", 80 | task.id(), 81 | elapsed 82 | ) 83 | } 84 | Progress::Error(err) => { 85 | println!("{}", err) 86 | } 87 | }); 88 | 89 | if task.is_done() { 90 | vec_opt_tasks[i] = None; 91 | count_down -= 1; 92 | } 93 | } 94 | } 95 | 96 | if count_down == 0 { 97 | break; 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /examples/fltk_fetch_ureq/src/main.rs: -------------------------------------------------------------------------------- 1 | use asynchron::{Futurize, ITaskHandle, Progress, SyncState}; 2 | use fltk::{*, app::*, button::*, frame::*, prelude::{GroupExt, WidgetExt}, window::*}; 3 | use std::time::Duration; 4 | use ureq::{Agent, AgentBuilder}; 5 | 6 | fn main() { 7 | let mut app = App::default(); 8 | app.set_scheme(Scheme::Gtk); 9 | let mut wind = Window::default().with_size(400, 300); 10 | wind.make_resizable(true); 11 | wind.set_label("Hello from rust"); 12 | 13 | let mut timer_frame = Frame::default().with_label(""); 14 | timer_frame.set_pos(0, 0); 15 | timer_frame.set_size(400, 100); 16 | 17 | let mut text_frame = 18 | Frame::default().with_label("Try hit Fetch button and let's see what happens..."); 19 | text_frame.set_pos(100, 60); 20 | text_frame.set_size(200, 200); 21 | 22 | let mut button_fetch = Button::default().with_label("Fetch"); 23 | button_fetch.set_pos(120, 210); 24 | button_fetch.set_size(80, 40); 25 | 26 | let mut button_cancel = Button::default() 27 | .with_label("Cancel") 28 | .right_of(&button_fetch, 10); 29 | button_cancel.set_size(80, 40); 30 | 31 | wind.show_with_args(&["-nokbd"]); 32 | 33 | let url = SyncState::new("https://www.rust-lang.org"); 34 | let _url = url.clone(); 35 | 36 | let request = Futurize::task(0, move |this: ITaskHandle| -> Progress { 37 | let url = match _url.load() { 38 | Some(url) => url, 39 | _ => return Progress::Error("Unable to load URL, probably empty.".into()), 40 | }; 41 | 42 | let agent: Agent = AgentBuilder::new() 43 | .timeout_read(Duration::from_secs(3)) 44 | .timeout_write(Duration::from_secs(3)) 45 | .build(); 46 | 47 | let req = agent.get(url); 48 | let res = match req.call() { 49 | Ok(res) => res, 50 | Err(e) => return Progress::Error(e.to_string().into()), 51 | }; 52 | 53 | // Check if progress is canceled 54 | if this.should_cancel() { 55 | return Progress::Canceled; 56 | } 57 | 58 | for _ in 0..5 { 59 | // Check if the task is canceled. 60 | if this.should_cancel() { 61 | return Progress::Canceled; 62 | } 63 | this.send(res.status()); 64 | std::thread::sleep(Duration::from_millis(100)) 65 | } 66 | 67 | if res.status() == 200 { 68 | // And check here also. 69 | if this.should_cancel() { 70 | Progress::Canceled 71 | } else { 72 | match res.into_string() { 73 | Ok(text) => { 74 | // and check here also. 75 | if this.should_cancel() { 76 | return Progress::Canceled; 77 | } 78 | Progress::Completed(text[0..100].to_string()) 79 | } 80 | Err(e) => return Progress::Error(e.to_string().into()), 81 | } 82 | } 83 | } else { 84 | Progress::Error(format!("Network error, status: {}", res.status()).into()) 85 | } 86 | }); 87 | 88 | let request_fetch = request.handle(); 89 | let request_cancel = request.rt_handle(); 90 | 91 | button_fetch.set_callback(move |_| request_fetch.try_do()); 92 | 93 | button_cancel.set_callback(move |_| { 94 | if request_cancel.is_canceled() { 95 | println!("Canceled") 96 | } else { 97 | request_cancel.cancel() 98 | } 99 | }); 100 | 101 | let mut label = String::new(); 102 | let mut timer = 0; 103 | 104 | while app.wait() { 105 | request.try_resolve(|progress, done| { 106 | match progress { 107 | Progress::Current(task_receiver) => { 108 | button_fetch.set_label("Fetching..."); 109 | if let Some(value) = task_receiver { 110 | text_frame.set_label(&format!("status: {}", value)) 111 | } 112 | } 113 | Progress::Canceled => label = "Request canceled.".to_owned(), 114 | Progress::Completed(value) => label = value, 115 | Progress::Error(e) => { 116 | eprintln!("{}", &e); 117 | label = e.into() 118 | } 119 | } 120 | 121 | if done { 122 | text_frame.set_label(&label); 123 | button_fetch.set_label("Fetch") 124 | } 125 | }); 126 | 127 | if url.is_empty() { 128 | let value = if timer % 2 == 0 { 129 | "https://hyper.rs" 130 | } else { 131 | "https://www.rust-lang.org" 132 | }; 133 | url.store(value); 134 | println!("url restored."); 135 | } 136 | 137 | timer += 1; 138 | 139 | timer_frame.set_label(timer.to_string().as_ref()); 140 | wind.redraw(); 141 | app::sleep(0.011); 142 | app::awake(); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /examples/fltk_fetch_reqwest/src/main.rs: -------------------------------------------------------------------------------- 1 | use asynchron::{Futurize, ITaskHandle, Progress, SyncState}; 2 | use fltk::{app::*, button::*, frame::*, prelude::WidgetExt, window::*, *}; 3 | use reqwest::{Client, Response}; 4 | use std::time::Duration; 5 | use tokio::runtime::Builder; 6 | 7 | async fn fetch(url: &str, time_out: Duration) -> reqwest::Result { 8 | let client = Client::builder().timeout(time_out).build()?; 9 | let req = client.get(url).build()?; 10 | client.execute(req).await 11 | } 12 | 13 | fn main() -> std::io::Result<()> { 14 | let mut app = App::default(); 15 | app.set_scheme(Scheme::Gtk); 16 | let mut wind = Window::default().with_size(400, 300); 17 | wind.set_label("Hello from rust"); 18 | let mut timer_frame = Frame::default().with_label(""); 19 | timer_frame.set_pos(0, 0); 20 | timer_frame.set_size(400, 100); 21 | 22 | let mut text_frame = 23 | Frame::default().with_label("Try hit Fetch button and let's see what happens..."); 24 | text_frame.set_pos(100, 60); 25 | text_frame.set_size(200, 200); 26 | 27 | let mut button_fetch = Button::default().with_label("Fetch"); 28 | button_fetch.set_pos(120, 210); 29 | button_fetch.set_size(80, 40); 30 | let mut button_cancel = Button::default() 31 | .with_label("Cancel") 32 | .right_of(&button_fetch, 10); 33 | button_cancel.set_size(80, 40); 34 | 35 | wind.show_with_args(&["-nokbd"]); 36 | 37 | let url = SyncState::new("https://www.rust-lang.org"); 38 | let _url = url.clone(); 39 | 40 | let rt = Builder::new_multi_thread().enable_all().build()?; 41 | // Clone the runtime handle, so the rt still reusable for the other tasks if needed. 42 | let rt_handle = rt.handle().clone(); 43 | 44 | let reqwest = Futurize::task( 45 | 0, 46 | move |this: ITaskHandle| -> Progress { 47 | rt_handle.block_on(async { 48 | let url = match _url.load() { 49 | Some(url) => url, 50 | _ => return Progress::Error("Unable to load URL, probably empty.".into()), 51 | }; 52 | 53 | // Timeout connection for 5 seconds, so there's a noise if something goes wrong. 54 | let time_out = Duration::from_secs(5); 55 | 56 | let response = match fetch(url, time_out).await { 57 | Ok(response) => response, 58 | Err(e) => return Progress::Error(e.to_string().into()), 59 | }; 60 | 61 | for i in 0..5 { 62 | this.send(format!("checking status... {}", i)); 63 | std::thread::sleep(Duration::from_millis(100)) 64 | } 65 | 66 | if !response.status().is_success() { 67 | return Progress::Error(response.status().to_string().into()); 68 | } 69 | 70 | let status = response.status().to_string(); 71 | for _ in 0..5 { 72 | // check if the task is canceled. 73 | if this.should_cancel() { 74 | return Progress::Canceled; 75 | } 76 | this.send(status.clone()); 77 | std::thread::sleep(Duration::from_millis(100)) 78 | } 79 | 80 | match response.text().await { 81 | Ok(text) => { 82 | // and check here also. 83 | if this.should_cancel() { 84 | return Progress::Canceled; 85 | } 86 | Progress::Completed(text[0..100].to_string()) 87 | } 88 | Err(e) => return Progress::Error(e.to_string().into()), 89 | } 90 | }) 91 | }, 92 | ); 93 | 94 | let reqwest_fetch = reqwest.handle(); 95 | let reqwest_cancel = reqwest.rt_handle(); 96 | 97 | button_fetch.set_callback(move |_| reqwest_fetch.try_do()); 98 | 99 | button_cancel.set_callback(move |_| { 100 | if reqwest_cancel.is_canceled() { 101 | println!("canceled") 102 | } else { 103 | reqwest_cancel.cancel() 104 | } 105 | }); 106 | 107 | let mut label = String::new(); 108 | 109 | let mut timer = 0; 110 | 111 | while app.wait() { 112 | reqwest.try_resolve(|progress, done| { 113 | match progress { 114 | Progress::Current(task_receiver) => { 115 | button_fetch.set_label("Fetching..."); 116 | if let Some(value) = task_receiver { 117 | text_frame.set_label(&value) 118 | } 119 | } 120 | Progress::Canceled => label = "Request canceled.".to_owned(), 121 | Progress::Completed(value) => label = value, 122 | Progress::Error(e) => { 123 | eprintln!("{}", &e); 124 | label = e.into() 125 | } 126 | } 127 | 128 | if done { 129 | text_frame.set_label(&label); 130 | button_fetch.set_label("Fetch") 131 | } 132 | }); 133 | 134 | if url.is_empty() { 135 | let value = if timer % 2 == 0 { 136 | "https://hyper.rs" 137 | } else { 138 | "https://www.rust-lang.org" 139 | }; 140 | url.store(value); 141 | println!("url restored."); 142 | } 143 | 144 | timer += 1; 145 | 146 | timer_frame.set_label(timer.to_string().as_ref()); 147 | wind.redraw(); 148 | app::sleep(0.011); 149 | app::awake(); 150 | } 151 | Ok(()) 152 | } 153 | -------------------------------------------------------------------------------- /examples/fltk_parallel_plotters/src/main.rs: -------------------------------------------------------------------------------- 1 | // main source code taken from: https://github.com/fltk-rs/demos/tree/master/plotters 2 | 3 | use asynchron::{Futurize, Progress}; 4 | use fltk::{prelude::*, *}; 5 | use plotters::prelude::*; 6 | use plotters::style::Color; 7 | use plotters_bitmap::bitmap_pixel::RGBPixel; 8 | use plotters_bitmap::BitMapBackend; 9 | use std::error::Error; 10 | use std::time::SystemTime; 11 | 12 | const SAMPLE_RATE: f64 = 10_000.0; 13 | const FREAME_RATE: f64 = 30.0; 14 | const WIN_W: i32 = 420; 15 | const WIN_H: i32 = 480; 16 | 17 | fn main() -> Result<(), Box> { 18 | const W: usize = 420; 19 | const H: usize = 240; 20 | let fx: f64 = 1.0; 21 | let fy: f64 = 1.1; 22 | let xphase: f64 = 0.0; 23 | let yphase: f64 = 0.1; 24 | 25 | let plot1 = Futurize::task(0, move |this| -> Progress, ()> { 26 | let mut buf = vec![0u8; W * H * 3]; 27 | let root = 28 | BitMapBackend::::with_buffer_and_format(&mut buf, (W as u32, H as u32)) 29 | .unwrap() 30 | .into_drawing_area(); 31 | root.fill(&BLACK).unwrap(); 32 | 33 | let mut chart = ChartBuilder::on(&root) 34 | .margin(10) 35 | .set_all_label_area_size(30) 36 | .build_cartesian_2d(-1.2..1.2, -1.2..1.2) 37 | .unwrap(); 38 | 39 | chart 40 | .configure_mesh() 41 | .label_style(("sans-serif", 15).into_font().color(&GREEN)) 42 | .axis_style(&GREEN) 43 | .draw() 44 | .unwrap(); 45 | 46 | let cs = chart.into_chart_state(); 47 | drop(root); 48 | 49 | let mut data = Vec::new(); 50 | let start_ts = SystemTime::now(); 51 | let mut last_flushed = 0.0; 52 | 53 | loop { 54 | let epoch = SystemTime::now() 55 | .duration_since(start_ts) 56 | .unwrap() 57 | .as_secs_f64(); 58 | 59 | if let Some((ts, _, _)) = data.pop() { 60 | if epoch - ts < 1.0 / SAMPLE_RATE { 61 | std::thread::sleep(std::time::Duration::from_secs_f64(epoch - ts)); 62 | continue; 63 | } 64 | let mut ts = ts; 65 | while ts < epoch { 66 | ts += 1.0 / SAMPLE_RATE; 67 | let phase_x: f64 = 2.0 * ts * std::f64::consts::PI * fx + xphase; 68 | let phase_y: f64 = 2.0 * ts * std::f64::consts::PI * fy + yphase; 69 | data.push((ts, phase_x.sin(), phase_y.sin())); 70 | } 71 | } 72 | 73 | let phase_x = 2.0 * epoch * std::f64::consts::PI * fx + xphase; 74 | let phase_y = 2.0 * epoch * std::f64::consts::PI * fy + yphase; 75 | data.push((epoch, phase_x.sin(), phase_y.sin())); 76 | 77 | if epoch - last_flushed > 1.0 / FREAME_RATE { 78 | let root = BitMapBackend::::with_buffer_and_format( 79 | &mut buf, 80 | (W as u32, H as u32), 81 | ) 82 | .unwrap() 83 | .into_drawing_area(); 84 | let mut chart = cs.clone().restore(&root); 85 | chart.plotting_area().fill(&BLACK).unwrap(); 86 | 87 | chart 88 | .configure_mesh() 89 | .bold_line_style(&GREEN.mix(0.2)) 90 | .light_line_style(&TRANSPARENT) 91 | .draw() 92 | .unwrap(); 93 | 94 | chart 95 | .draw_series(data.iter().zip(data.iter().skip(1)).map( 96 | |(&(e, x0, y0), &(_, x1, y1))| { 97 | PathElement::new( 98 | vec![(x0, y0), (x1, y1)], 99 | &GREEN.mix(((e - epoch) * 20.0).exp()), 100 | ) 101 | }, 102 | )) 103 | .unwrap(); 104 | 105 | std::mem::forget(root); 106 | std::mem::forget(chart); 107 | last_flushed = epoch; 108 | } 109 | 110 | this.send(buf.to_owned()); 111 | 112 | while let Some((e, _, _)) = Some(data[0]) { 113 | if ((e - epoch) * 20.0).exp() > 0.1 { 114 | break; 115 | } 116 | std::mem::forget(data.remove(0)); 117 | } 118 | } 119 | }); 120 | 121 | let plot2 = Futurize::task(1, move |this| -> Progress, ()> { 122 | let mut buf = vec![0u8; W * H * 3]; 123 | let root = 124 | BitMapBackend::::with_buffer_and_format(&mut buf, (W as u32, H as u32)) 125 | .unwrap() 126 | .into_drawing_area(); 127 | root.fill(&BLACK).unwrap(); 128 | 129 | let mut chart = ChartBuilder::on(&root) 130 | .margin(10) 131 | .set_all_label_area_size(30) 132 | .build_cartesian_2d(-1.2..1.2, -1.2..1.2) 133 | .unwrap(); 134 | 135 | chart 136 | .configure_mesh() 137 | .label_style(("sans-serif", 15).into_font().color(&RED)) 138 | .axis_style(&RED) 139 | .draw() 140 | .unwrap(); 141 | 142 | let cs = chart.into_chart_state(); 143 | drop(root); 144 | 145 | let mut data = Vec::new(); 146 | let start_ts = SystemTime::now(); 147 | let mut last_flushed = 0.0; 148 | 149 | loop { 150 | let epoch = SystemTime::now() 151 | .duration_since(start_ts) 152 | .unwrap() 153 | .as_secs_f64(); 154 | 155 | if let Some((ts, _, _)) = data.pop() { 156 | if epoch - ts < 1.0 / SAMPLE_RATE { 157 | std::thread::sleep(std::time::Duration::from_secs_f64(epoch - ts)); 158 | continue; 159 | } 160 | let mut ts = ts; 161 | while ts < epoch { 162 | ts += 1.0 / SAMPLE_RATE; 163 | let phase_x: f64 = 2.0 * ts * std::f64::consts::PI * fx + xphase; 164 | let phase_y: f64 = 2.0 * ts * std::f64::consts::PI * fy + yphase; 165 | data.push((ts, phase_x.sin(), phase_y.sin())); 166 | } 167 | } 168 | 169 | let phase_x = 2.0 * epoch * std::f64::consts::PI * fx + xphase; 170 | let phase_y = 2.0 * epoch * std::f64::consts::PI * fy + yphase; 171 | data.push((epoch, phase_x.sin(), phase_y.sin())); 172 | 173 | if epoch - last_flushed > 1.0 / FREAME_RATE { 174 | let root = BitMapBackend::::with_buffer_and_format( 175 | &mut buf, 176 | (W as u32, H as u32), 177 | ) 178 | .unwrap() 179 | .into_drawing_area(); 180 | let mut chart = cs.clone().restore(&root); 181 | chart.plotting_area().fill(&BLACK).unwrap(); 182 | 183 | chart 184 | .configure_mesh() 185 | .bold_line_style(&RED.mix(0.2)) 186 | .light_line_style(&TRANSPARENT) 187 | .draw() 188 | .unwrap(); 189 | 190 | chart 191 | .draw_series(data.iter().zip(data.iter().skip(1)).map( 192 | |(&(e, x0, y0), &(_, x1, y1))| { 193 | PathElement::new( 194 | vec![(x0, y0), (x1, y1)], 195 | &RED.mix(((e - epoch) * 20.0).exp()), 196 | ) 197 | }, 198 | )) 199 | .unwrap(); 200 | 201 | std::mem::forget(root); 202 | std::mem::forget(chart); 203 | last_flushed = epoch; 204 | } 205 | 206 | this.send(buf.to_owned()); 207 | 208 | while let Some((e, _, _)) = Some(data[0]) { 209 | if ((e - epoch) * 20.0).exp() > 0.1 { 210 | break; 211 | } 212 | std::mem::forget(data.remove(0)); 213 | } 214 | 215 | // delay for 180 ms. 216 | std::thread::sleep(std::time::Duration::from_millis(180)); 217 | } 218 | }); 219 | 220 | let app = app::App::default(); 221 | let mut win = window::Window::default().with_size(WIN_W, WIN_H); 222 | let mut frame = frame::Frame::default().with_size(420, 240); 223 | let mut frame2 = frame::Frame::default() 224 | .with_size(420, 240) 225 | .below_of(&frame, 0); 226 | win.end(); 227 | win.show(); 228 | 229 | plot1.try_do(); 230 | plot2.try_do(); 231 | 232 | let mut count = 0; 233 | let mut assume_failure = false; 234 | 235 | let mut retry_plot2 = false; 236 | let mut retry_plot1 = false; 237 | 238 | while app.wait() { 239 | plot1.try_resolve(|prog, _| match prog { 240 | Progress::Current(recv) => { 241 | if let Some(_buf) = recv { 242 | draw::draw_rgb(&mut frame, &_buf).unwrap(); 243 | if !assume_failure { 244 | count += 1 245 | } 246 | } 247 | } 248 | Progress::Error(e) => { 249 | println!("{}\n", e); 250 | // unwrapping all over the place potentially panicked, retry? 251 | retry_plot1 = true 252 | } 253 | _ => (), 254 | }); 255 | 256 | if retry_plot1 { 257 | plot1.try_do(); 258 | retry_plot1 = false 259 | } 260 | 261 | if count >= 60 { 262 | count = 60; 263 | assume_failure = true; 264 | plot2.try_resolve(|prog, _| match prog { 265 | Progress::Current(recv) => { 266 | if let Some(_buf) = recv { 267 | draw::draw_rgb(&mut frame2, &_buf).unwrap(); 268 | } 269 | } 270 | Progress::Error(e) => { 271 | println!("{}\n", e); 272 | // unwrapping all over the place potentially panicked, retry? 273 | retry_plot2 = true 274 | } 275 | _ => (), 276 | }); 277 | 278 | if retry_plot2 { 279 | plot2.try_do(); 280 | retry_plot2 = false 281 | } 282 | } 283 | win.redraw(); 284 | app::sleep(0.017); 285 | app::awake(); 286 | } 287 | Ok(()) 288 | } 289 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![deny(unsafe_code)] 2 | use core::{ 3 | clone::Clone, 4 | fmt::{Debug, Formatter}, 5 | marker::PhantomData, 6 | sync::atomic::{AtomicBool, AtomicUsize, Ordering}, 7 | }; 8 | use std::{ 9 | borrow::Cow, 10 | sync::{Arc, Condvar, Mutex}, 11 | thread, 12 | }; 13 | 14 | const ZER: usize = 0; 15 | const TRU: bool = true; 16 | const FAL: bool = false; 17 | 18 | /// Result for Futurized task, 19 | /// 20 | /// where C: type of ITaskHandle sync sender value, T: type of Completed value, 21 | pub enum Progress<'a, C, T> { 22 | /// Current progress of the task 23 | Current(Option), 24 | /// Indicates if the task is canceled 25 | Canceled, 26 | Completed(T), 27 | Error(Cow<'a, str>), 28 | } 29 | 30 | impl<'a, C: Debug, T: Debug> Debug for Progress<'a, C, T> { 31 | fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { 32 | match self { 33 | Self::Current(val) => write!(f, "Current: {:?}", val), 34 | Self::Canceled => write!(f, "Canceled"), 35 | Self::Completed(val) => write!(f, "Completed: {:?}", val), 36 | Self::Error(val) => write!(f, "Error: {}", val), 37 | } 38 | } 39 | } 40 | 41 | impl<'a, C: Clone, T: Clone> Clone for Progress<'a, C, T> { 42 | fn clone(&self) -> Self { 43 | match self { 44 | Self::Current(val) => Self::Current(Clone::clone(val)), 45 | Self::Canceled => Self::Canceled, 46 | Self::Completed(val) => Self::Completed(Clone::clone(val)), 47 | Self::Error(val) => Self::Error(Clone::clone(val)), 48 | } 49 | } 50 | } 51 | 52 | /// Runtime handle of the task. 53 | pub struct RuntimeHandle { 54 | _id: usize, 55 | rt_states: Arc<(AtomicBool, AtomicBool, AtomicBool, AtomicBool)>, 56 | } 57 | 58 | impl Clone for RuntimeHandle { 59 | fn clone(&self) -> Self { 60 | let _self = self; 61 | Self { 62 | _id: _self._id, 63 | rt_states: Arc::clone(&_self.rt_states), 64 | } 65 | } 66 | } 67 | 68 | impl RuntimeHandle { 69 | /// Get the id of the task 70 | pub fn id(&self) -> usize { 71 | self._id 72 | } 73 | 74 | /// Send signal to the inner task handle that the task should be suspended, 75 | /// 76 | /// this won't do anything if not explicitly configured inside the task. 77 | pub fn suspend(&self) { 78 | self.rt_states.3.store(TRU, Ordering::Relaxed) 79 | } 80 | 81 | /// Resume the suspended task. 82 | pub fn resume(&self) { 83 | self.rt_states.3.store(FAL, Ordering::Relaxed) 84 | } 85 | 86 | /// Check if progress of the task is resumed. 87 | pub fn is_resumed(&self) -> bool { 88 | !self.rt_states.3.load(Ordering::Relaxed) 89 | } 90 | 91 | /// Check if progress of the task is suspended. 92 | pub fn is_suspended(&self) -> bool { 93 | self.rt_states.3.load(Ordering::Relaxed) 94 | } 95 | 96 | /// Send signal to the inner task handle that the task should be canceled. 97 | /// 98 | /// this won't do anything if not explicitly configured inside the task. 99 | pub fn cancel(&self) { 100 | self.rt_states.2.store(TRU, Ordering::Relaxed) 101 | } 102 | 103 | /// Check if progress of the task is canceled. 104 | pub fn is_canceled(&self) -> bool { 105 | self.rt_states.2.load(Ordering::Relaxed) 106 | } 107 | 108 | /// Check if the task is in progress. 109 | pub fn is_in_progress(&self) -> bool { 110 | self.rt_states.0.load(Ordering::Relaxed) 111 | } 112 | 113 | /// Check if the task isn't in progress anymore (done). 114 | pub fn is_done(&self) -> bool { 115 | !self.rt_states.0.load(Ordering::Relaxed) 116 | } 117 | } 118 | 119 | /// Inner handle of the task, 120 | /// 121 | /// where C: type of sync sender value. 122 | pub struct ITaskHandle { 123 | _id: usize, 124 | rt_states: Arc<(AtomicBool, AtomicBool, AtomicBool, AtomicBool)>, 125 | sync_s: Arc<(AtomicBool, Mutex>, Condvar)>, 126 | } 127 | 128 | impl Clone for ITaskHandle { 129 | fn clone(&self) -> Self { 130 | let _self = self; 131 | Self { 132 | _id: _self._id, 133 | rt_states: Arc::clone(&_self.rt_states), 134 | sync_s: Arc::clone(&_self.sync_s), 135 | } 136 | } 137 | } 138 | 139 | impl ITaskHandle { 140 | /// Send current progress of the task. 141 | /// 142 | pub fn send(&self, t: C) { 143 | let (ready, mtx, cvar) = &*self.sync_s; 144 | if let Ok(mut mtx) = mtx.lock() { 145 | *mtx = Some(t); 146 | ready.store(TRU, Ordering::Relaxed); 147 | let _ = cvar.wait(mtx); 148 | } 149 | } 150 | 151 | /// Get the id of the task 152 | pub fn id(&self) -> usize { 153 | self._id 154 | } 155 | 156 | /// Check if progress of the task should be suspended, 157 | /// 158 | /// usually applied for a specific task with event loop in it. 159 | /// 160 | /// do other things (switch) while the task is suspended. 161 | pub fn should_suspend(&self) -> bool { 162 | self.rt_states.3.load(Ordering::Relaxed) 163 | } 164 | 165 | /// Check if progress of the task should be canceled. 166 | pub fn should_cancel(&self) -> bool { 167 | self.rt_states.2.load(Ordering::Relaxed) 168 | } 169 | } 170 | 171 | impl Drop for ITaskHandle { 172 | fn drop(&mut self) { 173 | if thread::panicking() { 174 | self.rt_states.1.store(TRU, Ordering::Relaxed) 175 | } 176 | } 177 | } 178 | 179 | /// Type name of ITaskHandle, 180 | /// 181 | /// 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. 182 | pub type InnerTaskHandle = ITaskHandle<()>; 183 | 184 | /// Handle of the task. 185 | pub struct TaskHandle { 186 | _id: usize, 187 | states: Arc<( 188 | Box) -> Progress<'static, C, T>>, 189 | Mutex>, 190 | AtomicBool, 191 | AtomicUsize, 192 | )>, 193 | rt_states: Arc<(AtomicBool, AtomicBool, AtomicBool, AtomicBool)>, 194 | sync_s: Arc<(AtomicBool, Mutex>, Condvar)>, 195 | } 196 | 197 | impl Clone for TaskHandle { 198 | fn clone(&self) -> Self { 199 | let _self = self; 200 | Self { 201 | _id: _self._id, 202 | states: Arc::clone(&_self.states), 203 | rt_states: Arc::clone(&_self.rt_states), 204 | sync_s: Arc::clone(&_self.sync_s), 205 | } 206 | } 207 | } 208 | 209 | impl TaskHandle 210 | where 211 | C: Clone + Send + 'static, 212 | T: Clone + Send + 'static, 213 | { 214 | /// Get the id of the task 215 | pub fn id(&self) -> usize { 216 | self._id 217 | } 218 | 219 | /// Set stack size (in bytes) of the thread for spawning Futurized task, 220 | /// 221 | /// Rust's official doc: https://doc.rust-lang.org/std/thread/struct.Builder.html#method.stack_size 222 | /// 223 | /// if the given value is zero or default, it will use Rust's standard stack size. 224 | pub fn stack_size(&self, size: usize) { 225 | self.states.3.store(size, Ordering::Relaxed) 226 | } 227 | 228 | /// Try (it won't block the current thread) to do the task now, 229 | /// 230 | /// and then try to resolve later. 231 | pub fn try_do(&self) { 232 | let waiting = &self.rt_states.0; 233 | if !waiting.load(Ordering::SeqCst) { 234 | waiting.store(TRU, Ordering::SeqCst); 235 | let _self = self; 236 | _self.rt_states.2.store(FAL, Ordering::Relaxed); 237 | let _stack_size = _self.states.3.load(Ordering::Relaxed); 238 | let states = Arc::clone(&_self.states); 239 | let inner_task_handle = ITaskHandle { 240 | _id: _self._id, 241 | rt_states: Arc::clone(&_self.rt_states), 242 | sync_s: Arc::clone(&_self.sync_s), 243 | }; 244 | let task = move || { 245 | let (closure, mtx, ready, _) = &*states; 246 | let result = closure(inner_task_handle); 247 | if let Ok(mut mtx) = mtx.lock() { 248 | *mtx = result; 249 | } 250 | ready.store(TRU, Ordering::Relaxed) 251 | }; 252 | if _stack_size == ZER { 253 | thread::spawn(task); 254 | } else { 255 | // Should panic if the given stack size value is incorrect, so it's better to unwrap() here. 256 | thread::Builder::new() 257 | .stack_size(_stack_size) 258 | .spawn(task) 259 | .unwrap(); 260 | } 261 | } 262 | } 263 | 264 | /// Send signal to the inner task handle that the task should be suspended. 265 | /// 266 | /// this won't do anything if not explicitly configured inside the task. 267 | pub fn suspend(&self) { 268 | self.rt_states.3.store(TRU, Ordering::Relaxed) 269 | } 270 | 271 | /// Resume the suspended task. 272 | pub fn resume(&self) { 273 | self.rt_states.3.store(FAL, Ordering::Relaxed) 274 | } 275 | 276 | /// Check if progress of the task is suspended. 277 | pub fn is_suspended(&self) -> bool { 278 | self.rt_states.3.load(Ordering::Relaxed) 279 | } 280 | 281 | /// Check if progress of the task is resumed. 282 | pub fn is_resumed(&self) -> bool { 283 | !self.rt_states.3.load(Ordering::Relaxed) 284 | } 285 | 286 | /// Send signal to the inner task handle that the task should be canceled. 287 | /// 288 | /// this won't do anything if not explicitly configured inside the task. 289 | pub fn cancel(&self) { 290 | self.rt_states.2.store(TRU, Ordering::Relaxed) 291 | } 292 | 293 | /// Check if progress of the task is canceled. 294 | pub fn is_canceled(&self) -> bool { 295 | self.rt_states.2.load(Ordering::Relaxed) 296 | } 297 | 298 | /// Check if the task is in progress. 299 | pub fn is_in_progress(&self) -> bool { 300 | self.rt_states.0.load(Ordering::Relaxed) 301 | } 302 | 303 | /// Check if the task isn't in progress anymore (done). 304 | pub fn is_done(&self) -> bool { 305 | !self.rt_states.0.load(Ordering::Relaxed) 306 | } 307 | } 308 | 309 | /// Futurize task asynchronously. 310 | /// # Example: 311 | /// 312 | ///``` 313 | ///use asynchron::{Futurize, Futurized, ITaskHandle, Progress}; 314 | ///use std::{ 315 | /// io::Error, 316 | /// time::{Duration, Instant}, 317 | ///}; 318 | /// 319 | ///fn main() { 320 | /// let instant: Instant = Instant::now(); 321 | /// let task: Futurized = Futurize::task( 322 | /// 0, 323 | /// move |_task: ITaskHandle| -> Progress { 324 | /// // // Panic if need to. 325 | /// // // will return Error with a message: 326 | /// // // "the task with id: (specific task id) panicked!" 327 | /// // std::panic::panic_any("loudness"); 328 | /// let sleep_dur = Duration::from_millis(10); 329 | /// std::thread::sleep(sleep_dur); 330 | /// let result = Ok::( 331 | /// format!("The task with id: {} wake up from sleep", _task.id()).into(), 332 | /// ); 333 | /// match result { 334 | /// Ok(value) => { 335 | /// // Send current task progress. 336 | /// _task.send(value) 337 | /// } 338 | /// Err(e) => { 339 | /// // Return error immediately if something not right, for example: 340 | /// return Progress::Error(e.to_string().into()); 341 | /// } 342 | /// } 343 | /// 344 | /// if _task.should_cancel() { 345 | /// _task.send("Canceling the task".into()); 346 | /// return Progress::Canceled; 347 | /// } 348 | /// Progress::Completed(instant.elapsed().subsec_millis()) 349 | /// }, 350 | /// ); 351 | /// 352 | /// // Try do the task now. 353 | /// task.try_do(); 354 | /// 355 | /// let mut exit = false; 356 | /// loop { 357 | /// task.try_resolve(|progress, done| { 358 | /// match progress { 359 | /// Progress::Current(task_receiver) => { 360 | /// if let Some(value) = task_receiver { 361 | /// println!("{}\n", value) 362 | /// } 363 | /// // // Cancel if need to. 364 | /// // task.cancel() 365 | /// } 366 | /// Progress::Canceled => { 367 | /// println!("The task was canceled\n") 368 | /// } 369 | /// Progress::Completed(elapsed) => { 370 | /// println!("The task finished in: {:?} milliseconds\n", elapsed) 371 | /// } 372 | /// Progress::Error(e) => { 373 | /// println!("{}\n", e) 374 | /// } 375 | /// } 376 | /// 377 | /// if done { 378 | /// // This scope act like "finally block", do final things here. 379 | /// exit = true 380 | /// } 381 | /// }); 382 | /// 383 | /// if exit { 384 | /// break; 385 | /// } 386 | /// } 387 | ///} 388 | ///``` 389 | pub struct Futurize { 390 | _data: PhantomData<(C, T)>, 391 | } 392 | 393 | impl Futurize { 394 | /// Create new task. 395 | pub fn task(id: usize, f: F) -> Futurized 396 | where 397 | F: Send + Sync + Fn(ITaskHandle) -> Progress<'static, C, T> + 'static, 398 | { 399 | Futurized { 400 | _id: id, 401 | states: Arc::new(( 402 | Box::new(f), 403 | Mutex::new(Progress::Current(None)), 404 | AtomicBool::new(FAL), 405 | AtomicUsize::new(ZER), 406 | )), 407 | receiver: Arc::new((AtomicBool::new(FAL), Mutex::new(None), Condvar::new())), 408 | rt_states: Arc::new(( 409 | AtomicBool::new(FAL), 410 | AtomicBool::new(FAL), 411 | AtomicBool::new(FAL), 412 | AtomicBool::new(FAL), 413 | )), 414 | } 415 | } 416 | } 417 | 418 | /// Futurized task. 419 | pub struct Futurized { 420 | _id: usize, 421 | states: Arc<( 422 | Box) -> Progress<'static, C, T>>, 423 | Mutex>, 424 | AtomicBool, 425 | AtomicUsize, 426 | )>, 427 | receiver: Arc<(AtomicBool, Mutex>, Condvar)>, 428 | rt_states: Arc<(AtomicBool, AtomicBool, AtomicBool, AtomicBool)>, 429 | } 430 | 431 | impl Clone for Futurized { 432 | fn clone(&self) -> Self { 433 | let _self = self; 434 | Self { 435 | _id: _self._id, 436 | states: Arc::clone(&_self.states), 437 | receiver: Arc::clone(&_self.receiver), 438 | rt_states: Arc::clone(&_self.rt_states), 439 | } 440 | } 441 | } 442 | 443 | impl Futurized 444 | where 445 | C: Clone + Send + 'static, 446 | T: Clone + Send + 'static, 447 | { 448 | /// Set stack size (in bytes) of the thread for spawning Futurized task, 449 | /// 450 | /// Rust's official doc: https://doc.rust-lang.org/std/thread/struct.Builder.html#method.stack_size 451 | /// 452 | /// if the given value is zero or default, it will use Rust's standard stack size. 453 | pub fn stack_size(&self, size: usize) { 454 | self.states.3.store(size, Ordering::Relaxed) 455 | } 456 | 457 | /// Try (it won't block the current thread) to do the task now, 458 | /// 459 | /// and then try to resolve later. 460 | pub fn try_do(&self) { 461 | let waiting = &self.rt_states.0; 462 | if !waiting.load(Ordering::SeqCst) { 463 | waiting.store(TRU, Ordering::SeqCst); 464 | let _self = self; 465 | _self.rt_states.2.store(FAL, Ordering::Relaxed); 466 | let _stack_size = _self.states.3.load(Ordering::Relaxed); 467 | let states = Arc::clone(&_self.states); 468 | let inner_task_handle = ITaskHandle { 469 | _id: _self._id, 470 | rt_states: Arc::clone(&_self.rt_states), 471 | sync_s: Arc::clone(&_self.receiver), 472 | }; 473 | let task = move || { 474 | let (closure, mtx, ready, _) = &*states; 475 | let result = closure(inner_task_handle); 476 | if let Ok(mut mtx) = mtx.lock() { 477 | *mtx = result; 478 | } 479 | ready.store(TRU, Ordering::Relaxed) 480 | }; 481 | if _stack_size == ZER { 482 | thread::spawn(task); 483 | } else { 484 | // Should panic if the given stack size value is incorrect, so it's better to unwrap() here. 485 | thread::Builder::new() 486 | .stack_size(_stack_size) 487 | .spawn(task) 488 | .unwrap(); 489 | } 490 | } 491 | } 492 | 493 | /// Send signal to the inner task handle that the task should be suspended. 494 | /// 495 | /// this won't do anything if not explicitly configured inside the task. 496 | pub fn suspend(&self) { 497 | self.rt_states.3.store(TRU, Ordering::Relaxed) 498 | } 499 | 500 | /// Resume the suspended task. 501 | pub fn resume(&self) { 502 | self.rt_states.3.store(FAL, Ordering::Relaxed) 503 | } 504 | 505 | /// Check if progress of the task is suspended. 506 | pub fn is_suspended(&self) -> bool { 507 | self.rt_states.3.load(Ordering::Relaxed) 508 | } 509 | 510 | /// Check if progress of the task is resumed. 511 | pub fn is_resumed(&self) -> bool { 512 | !self.rt_states.3.load(Ordering::Relaxed) 513 | } 514 | 515 | /// Send signal to the inner task handle that the task should be canceled. 516 | /// 517 | /// this won't do anything if not explicitly configured inside the task. 518 | pub fn cancel(&self) { 519 | self.rt_states.2.store(TRU, Ordering::Relaxed) 520 | } 521 | 522 | /// Check if progress of the task is canceled. 523 | pub fn is_canceled(&self) -> bool { 524 | self.rt_states.2.load(Ordering::Relaxed) 525 | } 526 | 527 | /// Get the task handle, if only intended to try to do, 528 | /// 529 | /// check progress, cancel, suspend or resume the task, from inside moving closures, 530 | /// 531 | /// or from other threads to avoid (channel) synchronous Sender data races. 532 | pub fn handle(&self) -> TaskHandle { 533 | let _self = self; 534 | TaskHandle { 535 | _id: _self._id, 536 | states: Arc::clone(&_self.states), 537 | sync_s: Arc::clone(&_self.receiver), 538 | rt_states: Arc::clone(&_self.rt_states), 539 | } 540 | } 541 | 542 | /// Get the runtime handle, if only intended to check progress, cancel, 543 | /// 544 | /// suspend or resume the task from inside moving closures or from other threads. 545 | /// 546 | /// use this to avoid unnecessary cloning unused task values. 547 | pub fn rt_handle(&self) -> RuntimeHandle { 548 | let _self = self; 549 | RuntimeHandle { 550 | _id: _self._id, 551 | rt_states: Arc::clone(&_self.rt_states), 552 | } 553 | } 554 | 555 | /// Get the id of the task 556 | pub fn id(&self) -> usize { 557 | self._id 558 | } 559 | 560 | /// Try resolve the progress of the task, 561 | /// 562 | /// WARNING! to prevent from data races this fn should be called once at a time. 563 | pub fn try_resolve, bool) -> ()>(&self, f: F) { 564 | if self.rt_states.0.load(Ordering::Relaxed) { 565 | let mut done = false; 566 | let mut result = || { 567 | let _self = self; 568 | let (awaiting, task_panicked, _, suspended) = &*_self.rt_states; 569 | { 570 | if task_panicked.load(Ordering::Relaxed) { 571 | suspended.store(FAL, Ordering::Relaxed); 572 | task_panicked.store(FAL, Ordering::Relaxed); 573 | // fixes unsound problem, return error immediately if the task is panicked. 574 | done = true; 575 | return Progress::Error(Cow::Owned(format!( 576 | "the task with id: {} panicked!", 577 | _self._id 578 | ))); 579 | } 580 | } 581 | 582 | if awaiting.load(Ordering::Relaxed) { 583 | let _self = _self; 584 | { 585 | if _self.receiver.0.load(Ordering::Relaxed) { 586 | let (ready, mtx, cvar) = &*_self.receiver; 587 | let result = if let Ok(mut mtx) = mtx.lock() { 588 | let result = Clone::clone(&*mtx); 589 | *mtx = None; 590 | result 591 | } else { 592 | None 593 | }; 594 | ready.store(FAL, Ordering::Relaxed); 595 | cvar.notify_all(); 596 | return Progress::Current(result); 597 | } 598 | } 599 | 600 | let ready = &_self.states.2; 601 | if ready.load(Ordering::Relaxed) { 602 | suspended.store(FAL, Ordering::Relaxed); 603 | let mtx = &_self.states.1; 604 | // there's almost zero chance to deadlock, 605 | // already guarded + with 2 atomicbools (awaiting and ready), so it's safe to unwrap here. 606 | let mut mtx = mtx.lock().unwrap(); 607 | let result = Clone::clone(&*mtx); 608 | *mtx = Progress::Current(None); 609 | ready.store(FAL, Ordering::Relaxed); 610 | done = true; 611 | return result; 612 | } 613 | return Progress::Current(None); 614 | } 615 | Progress::Current(None) 616 | }; 617 | f(result(), done); 618 | if done { 619 | self.rt_states.0.store(FAL, Ordering::Relaxed); 620 | } 621 | } 622 | } 623 | 624 | /// Check if the task is in progress. 625 | pub fn is_in_progress(&self) -> bool { 626 | self.rt_states.0.load(Ordering::Relaxed) 627 | } 628 | 629 | /// Check if the task isn't in progress anymore (done). 630 | pub fn is_done(&self) -> bool { 631 | !self.rt_states.0.load(Ordering::Relaxed) 632 | } 633 | } 634 | 635 | /// Tricky oneshot thread safe state management 636 | /// 637 | /// WARNING! 638 | /// (if not sure how to use it, don't use it) 639 | /// 640 | /// using std::sync::Arc, std::sync::Mutex and core::option::Option under the hood. 641 | /// 642 | /// # Example: 643 | /// 644 | ///``` 645 | ///use asynchron::SyncState; 646 | /// 647 | ///fn main() -> core::result::Result<(), Box> { 648 | /// let state: SyncState = SyncState::new(0); 649 | /// let _state = state.clone(); 650 | /// 651 | /// // The state will be empty if it successfully loaded. 652 | /// match state.load() { 653 | /// Some(value) => { 654 | /// println!("initial value: {:?}", value) 655 | /// } 656 | /// _ => (), 657 | /// } 658 | /// 659 | /// assert_eq!(true, state.is_empty()); 660 | /// 661 | /// if let Err(_) = std::thread::spawn(move || { 662 | /// if _state.is_empty() { 663 | /// // Restore the state. 664 | /// _state.store(20) 665 | /// } 666 | /// }) 667 | /// .join() 668 | /// { 669 | /// let e = std::io::Error::new(std::io::ErrorKind::Other, "Unable to join the thread."); 670 | /// return Err(Box::new(e)); 671 | /// } 672 | /// 673 | /// if state.is_full() { 674 | /// match state.load() { 675 | /// Some(value) => { 676 | /// assert_eq!(value, 20); 677 | /// println!("latest value {:?}", value) 678 | /// } 679 | /// _ => { 680 | /// let e = std::io::Error::new(std::io::ErrorKind::Other, "State not restore."); 681 | /// return Err(Box::new(e)); 682 | /// } 683 | /// } 684 | /// } 685 | /// 686 | /// assert_eq!(true, state.is_empty()); 687 | /// 688 | /// Ok(()) 689 | ///} 690 | ///``` 691 | pub struct SyncState { 692 | item: Arc<(Mutex>, AtomicBool)>, 693 | } 694 | 695 | impl Clone for SyncState { 696 | fn clone(&self) -> Self { 697 | Self { 698 | item: Arc::clone(&self.item), 699 | } 700 | } 701 | } 702 | 703 | impl SyncState { 704 | /// Create new state. 705 | pub fn new(t: T) -> SyncState { 706 | SyncState { 707 | item: Arc::new((Mutex::new(Some(t)), AtomicBool::new(FAL))), 708 | } 709 | } 710 | 711 | /// Load new value from the state. 712 | pub fn load(&self) -> Option { 713 | if let Ok(mut mtx) = self.item.0.lock() { 714 | let result = Clone::clone(&*mtx); 715 | *mtx = None; 716 | self.item.1.store(TRU, Ordering::Relaxed); 717 | return result; 718 | } 719 | None 720 | } 721 | 722 | /// Store new value to the state 723 | pub fn store(&self, t: T) { 724 | if let Ok(mut value) = self.item.0.lock() { 725 | *value = Some(t); 726 | self.item.1.store(FAL, Ordering::Relaxed) 727 | } 728 | } 729 | 730 | /// Check if the state isn't full (if it isn't full, just store it). 731 | pub fn is_empty(&self) -> bool { 732 | self.item.1.load(Ordering::Relaxed) 733 | } 734 | 735 | /// Check if the state isn't empty (if it isn't empty, just load it). 736 | pub fn is_full(&self) -> bool { 737 | !self.item.1.load(Ordering::Relaxed) 738 | } 739 | } 740 | --------------------------------------------------------------------------------