Skip to content

for_each_init calls init several times per thread #742

@pchampin

Description

@pchampin

Here is my use case, I must process all elements of ts: Vec<T>, with a function f(&mut T, &mut Buffer). The Buffer type is long to allocate an initialize, but its state after executing f is guaranteed to be identical to the initial state. So my (single-threaded) loop looks like this:

let mut b = allocate_and_init_buffer();
for t in ts.iter_mut() {
    f(t, &mut b);
}

I would like to make this parallel. So I turned it to:

ts.par_iter_mut().for_each_init(
    allocate_and_init_buffer,
    |b, t| f(t, b);
});

This runs faster (thanks rayon 😄), but I noticed that allocate_and_init_buffer is called more times than the number of threads in the thread pool... I'm guessing that the threads get "reset" every once in a while, making it necessary to call the init function again?

Is there a way I can control how/when this "reset" occurs, in order to minimize the number of times allocate_and_init_buffer is called?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions