12 ms·
Rust 1.63
- GolDDranks 4y agoScoped threads are something that really showcases Rust's features around thread-safety, lifetimes, sharing and mutability. I'm glad it's finally back in the standard library!
- davidatbu 4y agoI would be very interested in hearing from experienced folks about how important this is/what useful patterns it unlocks. I ask because I remember when trying to learn Kotlin, the docs made a big deal of structured concurrency[0], and golang of course is known for its concurrency story. [0] https://kotlinlang.org/docs/coroutines-basics.html#structured-concurrency https://kotlinlang.org/docs/coroutines-basics.html#structure...
- masklinn 4y ago> I would be very interested in hearing from experienced folks about how important this is/what useful patterns it unlocks. For Rust it allows thread to play better with lifetimes, which means there are scenarios where you don’t need the overhead of a lock (and usually the Arc that does with it, unless you go with a global) or queue, you can just work with on-stack “unsynchronised” borrows and it’s thread safe. That means lower syntactic and runtime overhead in the cases where it’s an option. It was already available in crossbeam so it’s not novel novel, but not needing a dependency for it is useful still.
- davidatbu 4y agoThanks! I didn't know that it was already available in crossbeam, that helps a lot in understanding the significance of this feature.
- klabb3 4y agoSadly, this is only lexical scoping which means you can only borrow from the outer scope and not ad-hoc the normal way borrowing works in Rust. In short, this means that thread pools and async runtimes cannot use this feature to provide borrowing across tasks. We're still stuck with Arc-ing everything that crosses task boundaries. Prior to 1.0, there were "true" scoped threads (with a lifetime 'a on the join handle), which let you borrow from the parent thread. (This could have extended to tasks as well, had they been around.) unfortunately it wasn't safe together with the much more popular Arc/Rc, which wasn't 'static restricted, despite it's ability to cause cycles and leak. So those powerful scoped threads were removed and "destructors are not guaranteed to run in safe Rust" was formalized instead. Seeing how popular async became, I wonder if this was the only and right way to move forward. I'm not against Arcs, they have their place. But if you can use normal RAII it's much preferable.
- oconnor663 4y ago> async runtimes cannot use this feature to provide borrowing across tasks They can't use this function, but with some duplicated unsafe code they can still provide similar APIs for their callers, right? Things like this: https://github.com/jaboatman/tokio-scoped https://github.com/jaboatman/tokio-scoped
- thramp 4y agothe problem with this approaches like these that it requires blocking the runtime: https://github.com/jaboatman/tokio-scoped/blob/master/src/lib.rs#L229-L231 https://github.com/jaboatman/tokio-scoped/blob/master/src/li....
- klabb3 4y agoI just checked quickly so may be wrong, but it looks like they're pulling the same trick as with the new scoped threads, ie only lexical scoping. Note also that the scope function is blocking and called from within an async fn, which is normally not great for composability with other async code. That said, taking a step back it has crossed my mind that bringing back true scoping with unsafe in the impl might be an acceptable way forward, despite how upsetting this is to a lot of rustaceans. I think that the failure modes (ie triggering UB) for this case can be simply enumerated in a short list of "DON'Ts" (such as putting a scoped join handle in an Arc). OTOH, since leaking was formalized and explicitly allowed (heck, even borderline encouraged through mem::forget), god knows if people have exploited that for other cases in true Hyrum's law fashion, that breaks the abovementioned idea. They certainly had the right to.
- superkuh 4y ago
- matthews2 4y agoGentoo got Rust 1.62.1 (the previous release) only three days after it was announced on rust-lang.org.
- dboreham 4y agoIt's a fine line. Python world spent 10 years not using Python 3 features.
- throwaway894345 4y agoPython is interpreted—you have to write code that works on all of your target platforms. Rust is compiled. You don’t have to care (much) about what is installed on your target platforms.
- hojjat12000 4y agoExcept for Libc. I compiled a rust program on Ubuntu 20.04 and tried to run it on Ubuntu 18.04, and bam.... a piano fell on my head! Consequences.
- sophacles 4y agoHow is this any different from C?
- throwaway894345 4y agoYeah, that was the “(much)” in my comment. Pretty sure you can statically link some libc or another though.
- nazgulsenpai 4y agoThis sounds more like an argument against the package manager maintainer for a Linux distribution rather than a Rust problem.
- Lvl999Noob 4y agoAwesome update! It's good to see scoped threads here. Btw, can someone explain how these are safe when the initial implementation wasn't? The problem was that someone could put a reference to a local variable inside an `Rc` or `Arc` and leak it with reference cycles, right? How is that case prevented now?
- kam 4y ago`std::thread::scope` takes a closure, and joins the threads after the call to the closure returns, rather than relying on `Drop`.
- game-of-throws 4y agoSide note: since memory leaks were deemed safe, there are easier ways to deliberately leak than using reference cycles. The most straightforward are `mem::forget` and `Box::leak`.
- duckerude 4y agoThe original implementation gave out a handle that waited for all the threads to end when it was dropped (i.e. went out of scope). That would prevent premature cleanup. But it was possible to leak the handle so that it would never be dropped even at the end of the block, and then it wouldn't wait for the threads. The new implementation calls a closure and waits for the threads when that closure returns. Unlike the destructor here's no way to stop that code from running when it should.
- deleted 4y ago[deleted]
- deleted 4y ago[deleted]
- brundolf 4y agoWow this is a juicy one
- csomar 4y agoThis is a huge update! At least, for me, I can see several things on my code base that could be changed because of this. (The first one is the lazy initialization of sync primitives; and the second one is BorrowedFd/OwnedFd.
- kibwen 4y agoHaving the new borrow checker finally on in all cases is nifty. For valid programs the behavior is the same as the previous version, but in the event of a compiler error, previous versions would still show you the output of the old borrow checker. I've already had one case where someone came asking about a confusing borrow checker error message and I just had to suggest that they try compiling with 1.63 and the new error message was clear enough that it answered their question immediately. Now we just need to do it all over again once Polonius finally arrives. :P
- brundolf 4y agoMigrations aren't ideal, but I'm excited to see continued innovation in borrow-checking. This is a major area where Rust is exploring truly new territory as a language, so growing pains are to be expected, and it's encouraging to me that Rust's semantics allow borrow checking to keep getting better without breaking changes
- cwzwarich 4y ago> it's encouraging to me that Rust's semantics allow borrow checking to keep getting better without breaking changes Just to be clear, these are breaking changes. If the new borrow checker didn’t break existing code, they would have removed the old one long ago. They’ve just decided that the observable effects of the breaking change in the ecosystem are small enough (especially after warning about them for years) that they are okay making the breaking change without a semver-incrementing Rust 2.0. To be fair, the reason for the breaking changes is generally to fix soundness issues (of course, not every example of code now banned will exhibit unsoundness), but that doesn’t cover all of them. There were some completely sound (albeit useless) examples of partial initialization that broke with NLL: https://github.com/rust-lang/rust/issues/21232#issuecomment-427152371 https://github.com/rust-lang/rust/issues/21232#issuecomment-... https://github.com/rust-lang/rust/issues/54987 https://github.com/rust-lang/rust/issues/54987 Strict adherence to semver would require still accepting this code.
- brundolf 4y ago
- baby 4y agoso const Mutex means you can do this IIUC: const THING: Mutex<u64> = Mutex::new(4); without using the once_cell crate. This is pretty cool! Also I realize that the Rust playground is still using 1.62.0 https://play.rust-lang.org/?version=beta&mode=debug&edition=2021&gist=26f120429fc724b038103235d9884cf1 https://play.rust-lang.org/?version=beta&mode=debug&edition=...
- shepmaster 4y agoWouldn’t you want to use static instead of const, otherwise you might get a new unique mutex at each usage? I think there’s a Clippy lint for that. The playground rebuilds overnight (roughly after the nightly is released); releases don’t have as fixed timing so I tend to trigger a rebuild when I notice. This HN post was delivered before the git tag was published even, so I’ve started it. Playground is updated now.
- tialaramex 4y agoYes. If I say FOUR is a const Mutex with a 4 in it, whenever I talk about FOUR I get a completely new unlocked Mutex with a 4 in it, unrelated to any other Mutex regardless of whether it was made the same way. This might be what you want if you, for some reason, need to make different Mutexes with a 4 in them all the time. But, if you actually meant one Mutex, which intially has a 4 in it, then that's a static variable not a constant. https://play.rust-lang.org/?version=beta&mode=debug&edition=2021&gist=6639e3f2e7cdc6ae18b47b19ea2ccec2 https://play.rust-lang.org/?version=beta&mode=debug&edition=... Change FOUR to be static instead of const, and now when we print y each time it's gone up by ten because we're using the same Mutex which is what we presumably intended.
- baby 4y agoWhat's the difference between CONST and STATIC fundamentally?
- notpopcorn 4y agoA const is like a `#define` in C or C++, while a static is a global variable.
- chmod600 4y agoWith the "try_reserve" stabilizations, does that mean the "allocator_api" is closer to stabilization?
- kibwen 4y agoI think that is less about the general allocator API than it is about the fallible allocation for collections RFC ( https://github.com/rust-lang/rust/issues/48043 https://github.com/rust-lang/rust/issues/48043 ), which is something that the Rust-in-Linux folks have been pushing for recently.
- ActorNightly 4y agoI wish they would stop adding features and just to lock down the language, and focus on more maintainability and use. Adding features is nice but its one of the biggest issues that slows down adoption. More people care about learning a language and being able to read code without trying to figure out what some latest feature does rather than some syntactical sugar.
- brundolf 4y agoMost of the features here (and in Rust updates in general these days) are just the loosening of constraints on what you could already do. If anything, these types of changes make the language conceptually simpler. This gets pointed out by somebody in the comment section under every Rust update. The trope that Rust is getting harder to use is tired, and not really based in reality.
- ActorNightly 4y agoDifferent syntax = different ways of doing things = codebases that diverge in implementation. It doesn't matter if the new way doing things is conceptually simpler, you are now creating 2 ways to do things based on what version of the compiler you use, which people will have to know, therefore increasing complexity, not reducing it. I don't understand how people don't get this by now. Saying "oh just learn and use the latest version" is completely unrealistic guidance. And while its fine for high level scripting languages like Python, because the whole idea is to abstract a lot of the functionality into the syntax, the issue with Rust is that its trying to be the next C and be applicable for writing critically important pieces of software like parts of the linux kernel. You absolutely must have a locked down language set for this. The reason C is still used for the kernel isn't because of circumstances, its specifically because there is very few ambiguities in the core language.
- brundolf 4y ago> you are now creating 2 ways to do things based on what version of the compiler you use Which of the features in Rust 1.63 adds a divergent way of doing something you could already do? > The reason C is still used for the kernel isn't because of circumstances, its specifically because there is very few ambiguities in the core language What are some ambiguities in the core Rust language?
- ydnaclementine 4y agoWhat is everyone building in rust, and how do the killer rust features (mentioned in other comments) help you? I'm not anti rust in any way, it's more of having limited time and so many languages problem. But I'm interested in the types of problems rust is good for, so I could consider it if/when I encounter them
- pjmlp 4y agoOnly hobby coding. Java, .NET languages and C++ are what pay the bills for me.
- mathstuf 4y agoI've used it to build two "bulletproof" services that are never intended to go down (the first catches webhook events and puts them to disk and should never go down; the second processes the on-disk files separately so that reloading the configuration can't cause us to miss webhook events). It is far nicer to have error handling as a visible part of the workflow so that you don't get "whoops, didn't consider that" situations (we had this constantly in the Python predecessor that had problems with "uh, you forgot to mention this might not be pure-ASCII, so I'm going to fall over now" problems as various fields popped up with Unicode over time). Best parts IMO (not in any order and not exhaustive): - Not having to consider exceptions (panics are still there, but are much closer to the "exceptional" behavior exceptions are/were meant to convey) - Explicit error handling with (usually) good error types/representation (instead of the nebulous "`err` that is a string" I've seen in what little Golang I've done) - Threading without worrying about race conditions - Dependency management - Data structure focused (instead of object focused) - The built-in `#[test]` features are also great and make it easy to test internal code without exposing it in some strange way purely for testing purposes. FWIW, I find that it also makes your C++ far better because now you can more easily "see" lifetime problems that people tend to write out of habit (`return stackstr.c_str();` is a…favorite that compilers now warn about).
- shpongled 4y agoI'm building scientific software in Rust. Phenomenal performance, drop-in concurrency support (`iter()` -> `par_iter()` with Rayon), and a great ML-based type system that makes writing correct code easy. It also has some of the best developer UX/tooling out of any language I've used.
- aendruk 4y agoIt’s a small thing, but array::from_fn makes me happy.
- svnpenn 4y agoWhy does it arbitrarily choose length 5? https://doc.rust-lang.org/core/array/fn.from_fn.html https://doc.rust-lang.org/core/array/fn.from_fn.html
- aendruk 4y agoIn that example N is inferred from the assertion; observing the output has affected it.
- svnpenn 4y agoWow that is stupid. That is way too much assumption.
- surewe 4y agoSure, it's a lot of assumption, but the type system would prevent an invalid assumption from compiling (arrays are typed [T; N] where T is the type they hold and N is the number of elements), and you can always override it with a turbofish.
- dymk 4y agohttps://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_sy... It's a dream once you understand it. You don't need to understand the math, just the general concept of type unification, and that type inference can flow in "both directions", as opposed to in e.g. C++ where `auto` inference only works in one direction. Rust is not exactly HM type inference, but it's something close to it. http://smallcultfollowing.com/babysteps/blog/2014/07/09/an-experimental-new-type-inference-scheme-for-rust/ http://smallcultfollowing.com/babysteps/blog/2014/07/09/an-e...
- chrismorgan 4y ago
- joshsyn 4y ago
- rvcdbn 4y agoHow come the first example isn’t a race on a since it’s accessed from two threads?
- jcranmer 4y agoBoth threads are only reading the array. For it to be a race, at least one of the accesses must be a write.
- rvcdbn 4y agoah, that makes sense thanks
- theptip 4y agoThe second usage is a mut borrow and I think would be incompatible with a read only borrow if they were run in parallel. As the comment eludes to, each spawned thread is implicitly joined if you drop the join handle returned by s::spawn(). So in this case the spawned threads run serially.
- DenseComet 4y agoNope, the threads run in parallel. The variable x is mutably borrowed only once by the second thread. The variable a is immutably borrowed twice, so there is no issue.
- theptip 4y agoAre you certain? From the docs on https://doc.rust-lang.org/stable/std/thread/struct.Scope.html#method.spawn https://doc.rust-lang.org/stable/std/thread/struct.Scope.htm..., > If the join handle is dropped, the spawned thread will implicitly joined at the end of the scope. Plus the comment says > // We can even mutably borrow `x` here, // because no other threads are using it. Which doesn’t line up with another thread having a read-only borrow on it. Anyway not at my machine to test right now, I could be wrong.
- jmartin2683 4y agoRust is the greatest. It’s my go-to for virtually anything that it could reasonably be used for (a lot). After using it exclusively for a while and getting comfortable and fast with it, I can’t see any good reason to use anything else for most purposes.
- pjmlp 4y agoGUI programming at the same level as MAUI, SwiftUI, Jetpack Compose, Qt, WPF,...
- jmartin2683 4y agoI will say thats one thing that I do absolutely none of. A lot of movement in that space, but clearly a lack of support on the level of C/C++.
- sebzim4500 4y agoYeah GUI is really the biggest missing part of the ecosystem. To be fair it is an extremely difficult problem; there is a reason there are so many electron apps out there.
- pjmlp 4y agoNot really, the reason is laziness and seeing nails everywhere, instead of picking the right tool. Coding GUI/TUIs since MS-DOS and Amiga 500 days, and Web since 1996.
- pas 4y agoA lot of times a cross platform non-native GUI is the right tool. Same UX on every platform. What's not to like? Allows faster iteration for small teams, you can use TS and doesn't even have to think about Swift/ObjC/Java/Kotlin/C++, and you can use whatever you like for the backend.
- pjmlp 4y ago
- mkaic 4y agoI'm a junior programmer who never went to college and writes Python for a living (ML researcher). I've been itching to learn another programming language, ideally something fast and low-level, and have had my eye on Rust now for some time. But in my brief experiments trying some of the docs' hello-world projects, I'm already finding myself a little out of my depth. I'm realizing I don't know anything about compilers and very little about how languages work on a technical level -- stuff like "strong" vs. "weak" typing, memory management, stacks and heaps and garbage collection -- I've seen all those terms before but have no intuition for what they mean. I never have to think about these concepts because Python is such a high-level "it just works" scripting language. Could anyone recommend some online resources for learning about the computer science of programming for someone with little prior experience? I'm not quite sure where to even start, but I'm eager to learn because at the moment I don't really feel like a "real programmer", more like a script kiddie. Heck, I only learned to use Git properly like 6 months ago!
- whb07 4y agoCS50X is a great starting point as they talk about the intro into bits/heap/stack etc. In the first half they have the work using C which will show you how to think about all this. I'd suggest doing the C parts and stopping at the python side. Once you stop, step into Rust and you'll see how much easier it is to perform all the things you were doing in C.
- Scarbutt 4y ago'The C programming language' and then 'Operating Systems: Three Easy Pieces'