stevedonovan/gentle-intro

thread5.rs does not need Arc

Opened this issue · 9 comments

It runs fine if I remove Arc wrapper. This is 7-shared-and-networking.md

This is very true! Although in your case, actual copies of the string are passed to each thread, and the Arc case shared references are passed. Would only notice if the string was truly enormous! So let me think how to frame this example where the difference is more obvious.

Perhaps also use a struct (that doesn't implement Copy) so the benefit of Arc is clear. WIth a String, one can just use a &str, ending up not needing the owned variety to see the benefit. Am not sure though if I understand this well?

If we used a &str reference originally, then we'll always get a 'does not live long enough' error. Putting the reference into an Arc doesn't help that - it remains a reference. I think I will emphasize that the clone here is much cheaper in the Arc case.

Have a look at the change - you can still clone the reference even if the value itself doesn't implement Clone.

I din't get the long life complaint when I used &str. See https://gist.github.com/tshepang/237d547c38e435144d6fe1887068d33e.

Puzzled me until I realized that &str is indeed Copy, so it moves just fine. It works because the lifetime of the string slice is static - if we pulled a slice out of a local string, then you would get the error:

    let string = "dolly".to_string();
    let name: &str = &string;

This would also work, const NAME: &str = "hello". So it's all about references to our own objects that have less-than-static lifetime.

Rust is not easy

Well, this has really helped me with a delicate piece of explanation. Ultimately, plain references don't work in threads because they have too short a lifetime to work with move closures. (Same problem with frameworks like gtk.rs). Same problem with C++ actually, except there is nothing stopping you pointing the gun at your foot. So in modern C++ people use std::shared_ptr, which is like Arc.