2 ms·
Indeed! Rust fails to notice that Arc cannot be accessed from different thread and makes unnecessary locked increment/decrement in add_two_numbers_smart_way().
by codedokode 4y ago
Indeed! Rust fails to notice that Arc cannot be accessed from different thread and makes unnecessary locked increment/decrement in add_two_numbers_smart_way().
- db48x 4y agoYour observation of the resulting output is correct, but not your conclusion about how it got there is not. The compiler doesn’t try to verify that the Arc is actually necessary, because there’s no point in optimizing the rare case where someone used an Arc but failed to Send it to another thread. The common case is that the author knows they won’t be sending it to another thread and so they use an Rc, or they know that they will so they use an Arc. The C++ language standard folks had to make a different choice. For historical reasons the C++ compiler is not able to prevent the program author from misusing a non–thread–safe smart pointer by sending it to another thread, so all smart pointers are required to be thread–safe. The compiler may try to optimize away the extra locking, and it may or may not succeed in any given program. It may not be able to prove that it is safe to do so even when you as the author know that it will be. Incidentally, every Rust program comes with a free test runner which is multithreaded; it runs multiple tests in parallel. This trips people up from time to time because the compiler will insist that certain types be thread–safe (tagged with the Send trait, in Rust) even though the author is not actually using any threads.
- brundolf 4y agoDoes the test runner actually pass any user-values between test threads?
- steveklabnik 4y agoNot on its own. It’s basically “hey take these functions, each is a test, run them on multiple threads” and that’s it, nothing fancier.
- db48x 4y agoRight. It just affects other decisions about the language, like the type of static items. In a purely single–threaded program it would be ok if statics weren’t Sync, but it would be a lot of work for the compiler to verify that. And since every program needs tests anyway, it might as well always require them to be Sync and then it doesn’t have to check.
- steveklabnik 4y agoTotally. I take a slightly different view in the statics thing; like a static means you want something to be available across threads. So by using a static, you’re opening yourself to that possibility. If you want something global to a thread, use thread local storage, and Rust will allow you to use stuff that’s not okay if multiple threads were involved. It’s about expressing your intent correctly.
- brundolf 4y agoTIL thread local storage!
- db48x 4y agoWhen I mentioned Send above, I meant Sync. I mix those two up more often in the evenings.