My goal : I just wanted to understand how to use shared state concurrency. Here, the process switches thread as soon as i update that data inside RwLock and when i use RwLock's read() method inside the main thread loop.
use std::{
os::unix::thread,
sync::{Arc, Mutex, RwLock},
time::Duration,
};
// Entry of the main thread, we are gonna draw the TUI
struct AppState {
currentValue: i32,
}
fn main() {
// Shared state
let sharedState = Arc::new(RwLock::new(AppState { currentValue: 0 }));
let threadData = Arc::clone(&sharedState);
let handle = std::thread::spawn(move || {
working_thread_main(threadData);
});
loop {
let readlock = sharedState.read().expect("Couldn't get read lock");
println!("{}", readlock.currentValue);
}
}
// Entry of the working thread, we are gonna work here
fn working_thread_main(
shared_state: Arc<RwLock<AppState>>,
) -> Result<(), Box<dyn std::error::Error>> {
let body = async move {
loop {
shared_state
.write()
.expect("Couldn't get write lock")
.currentValue += 1;
println!("HEre");
}
};
tokio::runtime::Runtime::new()?.block_on(body);
Ok(())
}
But the process doesn't switch the thread and work when i just get the read lock, outside of loop block in main thread.
use std::{
os::unix::thread,
sync::{Arc, Mutex, RwLock},
time::Duration,
};
// Entry of the main thread, we are gonna draw the TUI
struct AppState {
currentValue: i32,
}
fn main() {
// Shared state
let sharedState = Arc::new(RwLock::new(AppState { currentValue: 0 }));
let threadData = Arc::clone(&sharedState);
let handle = std::thread::spawn(move || {
working_thread_main(threadData);
});
let readlock = sharedState.read().expect("Couldn't get read lock");
loop {
println!("{}", readlock.currentValue);
}
}
// Entry of the working thread, we are gonna work here
fn working_thread_main(
shared_state: Arc<RwLock<AppState>>,
) -> Result<(), Box<dyn std::error::Error>> {
let body = async move {
loop {
shared_state
.write()
.expect("Couldn't get write lock")
.currentValue += 1;
println!("HEre");
}
};
tokio::runtime::Runtime::new()?.block_on(body);
Ok(())
}
FYI : I'm noob at rust
Can someone help me understand why the first one switches thread, and the second one doesn't?