When I\'m delegating work to threads I often have a piece of data that will outlive all of the threads, such as numbers
in the following example:
us
You might have the wrong idea: cloning an Arc
is just incrementing a reference counter and making a copy of a pointer; it doesn't perform any additional allocation. Of course, creating the Arc
involves an allocation, but then, you're already allocating in order to construct the Vec
, so one additional fixed-size allocation isn't likely to hurt.
If all you really need is the length, you can just compute that outside the thread's closure and store it in a variable; a usize
has no problems crossing a thread boundary.
The issue is that the compiler is unable to infer from the use of join()
that a given thread is bound to a limited lifetime... it doesn't even try.
Before Rust 1.0, there was a thread::scoped
constructor that allowed you to pass in non-'static
references, but that had to be de-stabilised due to a memory safety issue. See How can I pass a reference to a stack variable to a thread? for alternatives.