Is it possible to share data with threads without any cloning?

后端 未结 1 1161
感情败类
感情败类 2021-02-15 15:32

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         


        
1条回答
  •  独厮守ぢ
    2021-02-15 16:03

    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.

    0 讨论(0)
提交回复
热议问题