-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
examples: Add a multithread example that updates a SensorData cache
- Loading branch information
1 parent
a999413
commit 02341a7
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
use navigator_rs::Navigator; | ||
use std::sync::{Arc, Mutex, RwLock}; | ||
use std::thread::{self, sleep}; | ||
use std::time::Duration; | ||
|
||
fn main() { | ||
println!("Creating your SensorData cache!"); | ||
let sensor_data_lock = Arc::new(RwLock::new(navigator_rs::SensorData::default())); | ||
|
||
println!("Creating your navigator module!"); | ||
let nav = Arc::new(Mutex::new(Navigator::new())); | ||
|
||
println!("Setting up your navigator, ahoy!"); | ||
nav.lock().unwrap().init(); | ||
|
||
// This code block create a thread that updates the `sensor_data_lock` periodically. | ||
let sensor_update_thread_lock = sensor_data_lock.clone(); | ||
let navigator_lock = nav.clone(); | ||
let _ = thread::spawn(move || { | ||
loop { | ||
if let Ok(mut write_guard) = sensor_update_thread_lock.write() { | ||
*write_guard = navigator_lock.lock().unwrap().read_all(); | ||
// println!("Updated value: {:?}", *write_guard); | ||
} | ||
sleep(Duration::from_millis(10000)); | ||
} | ||
}); | ||
|
||
// This code block could be also other thread, but just run on the main one. | ||
// This could could work as a server get handler, or a instance that can be used by different services to monitor and analysis. | ||
loop { | ||
if let Ok(lock) = sensor_data_lock.read() { | ||
let value = lock; | ||
println!("Read SensorData: {:?}", value); | ||
} | ||
sleep(Duration::from_millis(1000)); | ||
} | ||
} |