Hi, I was asked to implement a function to compare two lists, which was sent in as '&' reference.
Considering that the two lists might be very large, so I decide to use multi-thread inside the function.
The code was like this:
fn isSub<T: PartialEq + Sync>(first_list: &'static [T], second_list: &'static [T]) -> bool {
let (tx, rx) = channel();
spawn(move || {
//something compare elements and send result to tx.
});
// something gets all results from rx and summarize.
// then make sure the thread has stopped using join, and return.
}
Then I was asked to make the lifetime of two params static, which is fully understandable. The compiler concerns that the memory of two params is recollected before the thread ends.
These are what I have known:
- I can use Box::leak() to get a static ref of the lists.
- or I need to change the way the params were sent in, like Arc.
But all of the above solution need to change the context. (the first one is preferred now, but it still causes several changes in the context), like this:
let huge: Vec<u32> = ...;
let huge_boxed = huge.into_boxed_slice();
let huge_ref = Box::leak(huge_boxed);
// then send huge_ref inside the function.
What I want to ask is:
In this case, I believe I know what I am doing and willing to take any consequences. Is there any way that no need to change the context. I mean like an unsafe way. I tried to use unsafe block and send pointer into the thread, but the compiler asked me not doing that, it said something like it's no safe to pass a *const T into a thread.
I hope I can know more about the unsafe feature in Rust, I think the unsafe part in the doc "The Rust Programming Language" maybe not fully covered.
Anyway, Rust is great, I'm now enjoying coding with it, thank you in advance.