Hello Rust community,
I'm trying to do something unusual and because I begin with rust, I don't manage to do it.
I try to do a library which creates a context for each thread.
Threads are managed by the application which uses my library.
I try to implement the following function:
struct Context {
t: i32
}
lazy_static! {
// Since it's mutable and shared, use mutex
static ref CONTEXTS: Mutex<HashMap<thread::ThreadId, Context>> = Mutex::new(HashMap::new());
}
fn get_context() -> &'static Context {
let guard = CONTEXTS.lock().unwrap();
let mut hashmap: HashMap<thread::ThreadId, Context> = *guard;
let context = hashmap.get(&thread::current().id());
match context {
Some(context) => context,
None => {
let c = Context{t:99};
hashmap.insert(thread::current().id(), c);
&hashmap.get(&thread::current().id()).unwrap()
}
}
}
What I want is simple: when you call get_context
, the function returns the Context
of this thread.
If the context doesn't exist, the function creates the Context
and returns it.
When I run this code, it doesn't work, like you can see here:
Could you help me to understand what is the proper way to implement this function ?
I tried to make it work for 5 hours without success.
Thanks in advance,
Sincerely,
Jean-Sébastien