Stage 2
move clone and locking to functions on tasklist
- refactor code into a nicer structure.
- add readable and writeable functions to my struct implementation so I can move the clone and sync into the structure
impl TaskList {
pub fn new() -> TaskList {
TaskList {
tasks : Arc::new(RwLock::new(TaskHashMap::new())),
}
}
pub fn readable(self) -> RwLockReadGuard<TaskHashMap>{
let tl = self.tasks.clone();
let mut my_tasks = tl.read().expect("RWLOCK poisoned");
my_tasks
}
pub fn writable(self) -> RwLockWriteGuard<TaskHashMap>{
let tl = self.tasks.clone();
let mut my_tasks = tl.write().expect("RWLOCK poisoned");
my_tasks
}
}
- turns out that this triggered lifetime issues - that is where I am at currently
- I need to specify a lifetime fo rthe hashmap which will guide the lifetimes for the readable/writable functions.
- Created minimal sample in Rust playground that produces the same errors
- https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=882b652a8dd423e40a55df79b6447342
- The interesting thing is, once I clear up the reported error I get the real issue
- https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=882b652a8dd423e40a55df79b6447342
pub fn readable<'rwlock>(self) -> RwLockReadGuard<'rwlock,TaskHashMap>{
let tl = self.tasks.clone();
let my_tasks = tl.read().expect("RWLOCK poisoned");
my_tasks
}
pub fn writable<'rwlock>(self) -> RwLockWriteGuard<'rwlock,TaskHashMap>{
let tl = self.tasks.clone();
let my_tasks = tl.write().expect("RWLOCK poisoned");
my_tasks
}
- The real issue is that the
RwLockWriteGuard
is actually based on the clone which is destroyed on the fn end. - This is something I didn’t see at first because I was distracted by the Rust but now the error is very clear
Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return value referencing local variable `tl`
--> src/lib.rs:28:3
|
27 | let my_tasks = tl.read().expect("RWLOCK poisoned");
| -- `tl` is borrowed here
28 | my_tasks
| ^^^^^^^^ returns a value referencing data owned by the current function
- When I look at the actual issue it is obvious, and I think that the lifetimes diversion actually did help uncover it
- I believe that in C++ I would have only found it at runtime and it might have been a bit tricky to find
- So this refactor is probably not going to work as I need to invoke the ARC clone (to get a shared object) in each thread.
- renamed a few things and set it back to working code.
Seems like a similar issue seen by this user in the error and that what I wanted to do wouldn’t be possible : https://users.rust-lang.org/t/returning-a-value-from-inside-a-cloned-arc-t/6903/3
Back to index page of the project is about getting the initial rust API running.