m-ou-se / rust-atomics-and-locks

Code examples, data structures, and links from my book, Rust Atomics and Locks.
Other
1.33k stars 120 forks source link

Anti-Pattern that I feel is a bit confusing #37

Open jaysonmaw opened 1 year ago

jaysonmaw commented 1 year ago

The content that the question is about

https://marabos.nl/atomics/basics.html#naming-clones

The question

This section contains the following code example:

let a = Arc::new([1, 2, 3]);

thread::spawn({
    let a = a.clone();
    move || {
        dbg!(a);
    }
});

dbg!(a);

I feel this is a bit confusing, especially to new users. At first glance this may be read as the arc clone happening on the second thread because it looks like you are passing the entire scope to the thread::spawn() function, when really the let a = a.clone(); line is still on the main thread.

In my opinion a better way of writing the same thing would be:

let a = Arc::new([1, 2, 3]);

{
    let a = a.clone();
    thread::spawn(move || {
        dbg!(a);
    })
};

dbg!(a);

This accomplishes the same thing but I think is less misleading and easier to understand at a glance, as well as making it more clear that the clone happens on the main thread.

Also sorry, not sure if this belongs under Technically Discussion, but putting it under error also didn't seem right as I thought maybe it was like this for a reason, very open to it staying as is if anyone sees it another way. Thanks for your hard work!