Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jaysonmaw opened this issue May 10, 2023 · 0 comments
Open

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

jaysonmaw opened this issue May 10, 2023 · 0 comments
Labels

Comments

@jaysonmaw
Copy link

jaysonmaw commented May 10, 2023

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant