Sign in to confirm you’re not a bot
This helps protect our community. Learn more
A Firehose of Rust, for busy people who know some C++
3.5KLikes
92,857Views
2021Jun 1
Slides: https://jacko.io/firehose_of_rust The slower version of this talk (2h32m):    • [SLOWER VERSION] A Firehose of Rust, for b...   Contents: 0:00:00 introduction 0:04:03 references and mutable aliasing 0:06:54 reference lifetime examples 0:22:12 mutable aliasing examples 0:50:16 move semantics 1:10:50 Arc Mutex String Links from screenshots in slides: https://godbolt.org/z/891s6z4Tb    • CppCon 2014: Herb Sutter "Back to the Basi...   https://godbolt.org/z/fK1WchMYf    • CppCon 2017: Louis Brandy “Curiously Recur...   Errata:
  • The example raw pointer code shown at 26:33 is valid today according to Miri, but it's not the best approach, and it's possible that it will become invalid before the rules for unsafe Rust finally stabilize. The worry is that creating a temporary shared reference on line 3 implies that the mutable reference on line 2 is definitely dead, which could mean that the raw pointer on line 2 is also dead in some sense. A more conservative approach would be to use .as_mut_ptr() to get a pointer to the first element and then .add() to get a pointer to the second element, without creating any extra references to the array. (Update: The "Tree Borrows" model for Miri also allows the example as written. https://perso.crans.org/vanille/treebor/)
  • At 56:20 I described both C++ copy constructors and the Rust .clone() method as making a "deep copy". That's sometimes the right way to think about it, but not when pointers and references get involved. Indeed, the final section relies on shallow cloning to share a reference-counted object across threads. C++ and Rust behave very similarly here, and understanding that ".clone() works like a C++ copy constructor" tells you most of what you need to know about a wide variety of different types.
  • At 1:05:49 I said that Mutex in Rust needs a heap allocation on Linux because of how the underlying system calls work. That's mostly incorrect. It's true that a futex can't be moved while locked, and that does matter for std::mutex in C++. But it doesn't actually matter in Rust, because a Mutex is borrowed and immovable while it's locked. Instead, the issue in Rust is that POSIX doesn't guarantee that a pthread_mutex_t is movable (although many implementations are movable in practice). See   / 1403413967846977538  . (Update: As of Rust 1.62, released in June 2022, Mutex on Linux creates a futex directly and no longer needs a heap allocation. Mutex still uses pthreads and heap allocation on some other Unix systems.)
  • At 1:15:13 I use Arc+Mutex to get the multithreaded Rust example working. That's a common idiom in Rust, and it's good to demo it, but as of Rust 1.63 (August 2022) you can also use "scoped" threads: https://doc.rust-lang.org/std/thread/...

Follow along using the transcript.

Jack O'Connor

2.94K subscribers