Hello world. My app needs a large amount of data, that takes a lot of time to be agregated, processed and updated. Then my strategy is to generate the data ahead of time and store it, so that when any part of my code needs the data, it just has to read the data source.
Here is my issue: as far as I know, the only way to get data from another module is to call a function. But the function itself can only access data that has been passed to it, or that it processed at call time. Then how can my modules share a common data source without storing it to the hard drive ?
I feel like these two statements somewhat contradict each other. If you want mutable access to a static variable, please use thread-safe interior mutability by wrapping the data in a Mutex or RwLock. See this answer for an example.
Ah, I see, I misinterpreted your first statement, my bad.
Note that with that sort of dynamic design (i.e. one part of your program generating the data and some other part(s) referencing it), I think it would be cleaner to do what @DanielKeep suggested and pass the data container explicitly down to your producers and consumers, rather than adding the indirection of a static variable. Rather than something like this:
use std::sync::Mutex;
use std::thread;
use std::time::Duration;
static DATA: Mutex<Vec<u8>> = Mutex::new(Vec::new());
fn producer() {
DATA.lock().unwrap().push(1);
}
fn consumer() {
let value = DATA.lock().unwrap().pop();
println!("{value:?}");
}
fn main() {
thread::spawn(producer);
thread::sleep(Duration::from_secs(1));
consumer();
}