Rayon par_iter() println! being ignored

#1
  1. I have the following code
    let lines: Vec<&str> = contents.split_whitespace().collect();
    println!("len: {:?}", lines.len());

    lines.par_iter().map(|s| {
            println!("line: {:?}", s);
        } );


    thread::sleep(std::time::Duration::from_secs(2));
  1. When I run it, I get output:

running 1 test
len: 15518
[[ 2 second delay ]]
test blahblah … ok

This confuses me. When I first ran this w/o the thread::sleep, there was no output, so I thought perhaps the parent thread finished before anything run. Now, however, I have added a thread::sleep for 2 seconds. Yet, I still get no output. What am I doing wrong?

#2

Apparently the solution is to add a .collect() as map doesn’t seem to execute right away.

1 Like
#3

Yep, iterators are lazy :wink:

1 Like
#4

That is an excellent thread. I recall reading that thread from a few days ago. I think a subconscious memory of that triggered me to try .collect().

Lesson learned .map is lazy.

2 Likes
#5

There should be a must_use warning in this case - did you not get that? That other thread would not have gotten the warning, because the iterator was in fact used, just lazily. But if you write a map that doesn’t even get assigned to anything, this should get a warning.

You can use for_each instead of map if you just want to execute something without collect.

5 Likes
#6

Iterator laziness is called out explicitly in the docs, but it only came to mind when collect() was mentioned. :joy: