Hi,
We are planning to implement concurrency between two threads, one for writing, another for creating a new connection.
In the main thread we want to take back the new connection by joining threads after "write" is performed.
We have a timer for 5 secs, on which we want to create a new connection and switch our existing connection with the new one according to the flag change.
We are facing issue with the thread spawning and its handler.
Pls suggest if there's a way to fix this.
use std::net::{TcpStream};
use std::io::{Read, Write};
use std::net::Shutdown;
use std::time::SystemTime;
use tokio::runtime::Runtime;
use std::{thread, time};
use std::sync::mpsc;
//#[tokio::main]
fn main(){
const addr:&str = "127.0.0.1:8000";
let mut tcp1 = TcpStream::connect(&addr);
let mut tcp2 = TcpStream::connect(&addr);
let mut tcp_timer_x = SystemTime::now();
let mut tcp_flag = 1;
//let rt = Runtime::new().unwrap();
let mut loopcount=0;
let mut timer_yes=0;
//let (tx, rx) = mpsc::channel();
loop{
**//-------- The issue is with the HANDLER here ---- //**
**//--------- handler here will spawn new threads on every iteration, which we must avoid.-------//**
let handler = thread::spawn(|| {
let tcpx = TcpStream::connect(&addr);
tcpx
});
let tcp_timer_y :u64= tcp_timer_x.elapsed().unwrap().as_secs().try_into().unwrap();
println!("Flag is: {:?} in line 21",tcp_flag);
if tcp_timer_y > 5{
**//------------ The issue with the handler here is that it is going out of scope when we use its return value later ------//**
// let handler = thread::spawn(|| {
// let tcpx = TcpStream::connect(&addr);
// tcpx
// });
timer_yes=1;
println!("Switching now -------- $$$$$$$$$$$$$");
if tcp_flag == 1 {
if tcp2.is_ok(){
println!("Changing flag at 2");
tcp_flag = 2;
}
}
else{
if tcp1.is_ok(){
println!("Changing flag at 1");
tcp_flag = 1;
}
}
tcp_timer_x = SystemTime::now();
}
let secs = time::Duration::from_secs(1);
thread::sleep(secs);
println!("Flag is: {:?} in line 62",tcp_flag);
if tcp_flag==1{
//check flag for new conn or not
match tcp1{
Ok(ref mut t)=>{
println!("TCP1: {:?}",t);
t.write("hey this is tcp1".as_bytes()).unwrap();
println!("// Send from tcp1 with loop {}",loopcount);
}
Err(ref e)=>{
println!("{:?}",e);
}
}
if timer_yes==1{
let tcp2 = handler.join().unwrap();
//tcp2 = rx.recv().unwrap();
timer_yes=0;
}
}
else{
match tcp2{
Ok(ref mut t)=>{
println!("TCP2: {:?}",t);
t.write("hey this is tcp2".as_bytes()).unwrap();
println!("// Send from tcp2 with loop {}",loopcount);
}
Err(ref e)=>{
println!("{:?}",e);
}
}
if timer_yes==1{
tcp1 = handler.join().unwrap();
//tcp1 = rx.recv().unwrap();
timer_yes=0;
}
}
loopcount+=1;
}
}