From c59941ad7dcfa3c8005473f92bae5086a5d9615b Mon Sep 17 00:00:00 2001 From: "Christoph J. Scherr" Date: Thu, 1 Feb 2024 10:39:52 +0100 Subject: [PATCH] tokryon bak --- members/tokryon/Cargo.toml | 11 ++++++++ members/tokryon/src/main.rs | 56 +++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 members/tokryon/Cargo.toml create mode 100644 members/tokryon/src/main.rs diff --git a/members/tokryon/Cargo.toml b/members/tokryon/Cargo.toml new file mode 100644 index 0000000..fe5cc5d --- /dev/null +++ b/members/tokryon/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "tokryon" +version = "0.0.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +futures = "0.3.30" +rayon = "1.8.1" +tokio = { version = "1.35.1", features = ["rt", "macros", "sync", "time", "rt-multi-thread"] } diff --git a/members/tokryon/src/main.rs b/members/tokryon/src/main.rs new file mode 100644 index 0000000..7de5d7a --- /dev/null +++ b/members/tokryon/src/main.rs @@ -0,0 +1,56 @@ +use std::sync::atomic::{AtomicU32, Ordering}; + +use rayon::prelude::*; +use tokio::{ + self, + time::{interval, Interval}, +}; + +static THE_NUMBER: AtomicU32 = AtomicU32::new(0); + +#[inline] +fn incr() { + // just add it + THE_NUMBER.store(THE_NUMBER.load(Ordering::Relaxed) + 1, Ordering::Relaxed) +} + +#[inline] +fn get() -> u32 { + THE_NUMBER.load(Ordering::Relaxed) +} +#[inline] +async fn more() { + rayon::spawn(|| incr()) +} + +#[tokio::main] +async fn main() { + // Lets say that we want to add numbers FAST + println!("The number: {THE_NUMBER:?}"); + incr(); + assert_eq!(get(), 1); + println!("The number: {THE_NUMBER:?}"); + println!("starting the threads"); + let mut interval = interval(tokio::time::Duration::from_millis(100)); + loop { + match future::select(do_work(), interval.tick()).await { + Either::Left((result, _)) => { + // Our worker completed successfully! + result?; + + // Do any additional processing here after successful completion + }, + + Either::Right(_) => { + // The interval has fired - we don't have to wait for the worker anymore + println!("Interval triggered!"); + } + }; + tokio::select! { + _ = interval.tick() => { + println!("The number: {THE_NUMBER:?}"); + } + _ = more() => () + }; + } +}