From 7d7b0577db7c4faf07d783f15a7794e85561b352 Mon Sep 17 00:00:00 2001 From: ennucore Date: Fri, 27 Mar 2020 21:40:38 +0300 Subject: [PATCH] Ways, receiving in threads in std environments is working --- src/transport.rs | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/transport.rs b/src/transport.rs index 2550660..f2efb1b 100644 --- a/src/transport.rs +++ b/src/transport.rs @@ -3,8 +3,11 @@ use crate::crypto::PublicKey; #[cfg(feature = "std")] use crate::way::Way; + #[cfg(feature = "std")] use std::thread; +#[cfg(feature = "std")] +use std::sync::{Arc, Mutex}; use alloc::vec::Vec; use alloc::boxed::Box; @@ -14,8 +17,8 @@ pub struct Transport {} #[cfg(feature = "std")] pub struct Transport { - ways: Vec>, - msg_pool: Vec, + pub ways: Vec>, + pub msg_pool: Vec, } #[cfg(not(feature = "std"))] @@ -36,7 +39,7 @@ impl Transport { #[cfg(feature = "std")] impl Transport { pub fn new() -> Self { - let transport = Self { ways: Vec::>::new(), msg_pool: Vec::::new() }; + let transport = Self { ways: Vec::>::new(), msg_pool: Vec::::new() }; transport } @@ -52,7 +55,8 @@ impl Transport { &crate::crypto::Keys::gen()), PublicKey { key: [1u8; 32] }) } - fn receive_through_way_in_loop_and_add_in_pool(&mut self, way: &mut Box) { + fn way_receiving_loop(&mut self, i: i32) { + let way = &self.ways[i as usize]; loop { let mut msg = way.receive(); self.msg_pool.push(msg); @@ -60,8 +64,13 @@ impl Transport { } fn start_receiving_thread(&'static mut self) { - thread::spawn(|| { - self.receive_through_way_in_loop_and_add_in_pool(&mut self.ways[0]); - }); + let way_num = self.ways.len(); + let transport = Arc::new(Mutex::new(self)); + for way in 0..way_num { + let current = transport.clone(); + thread::spawn(move || { + current.lock().unwrap().way_receiving_loop(way as i32); + }); + } } }