|
|
Log in / Subscribe / Register

Rust Keyword Generics Progress Report: February 2023

Rust Keyword Generics Progress Report: February 2023

Posted Feb 27, 2023 20:18 UTC (Mon) by NYKevin (subscriber, #129325)
In reply to: Rust Keyword Generics Progress Report: February 2023 by Wol
Parent article: Rust Keyword Generics Progress Report: February 2023

> Things like maybe have the same API for thread-safe and not-thread-safe, but something tells the compiler and it either forces the thread-safe implementation or blocks threads if the not-thread-safe implementation is used.

Rust already does that with the Send and Sync traits. If an object is not Send and/or Sync, then the compiler will know that it is thread-unsafe and refuse to let you share it between threads (the two traits refer to two slightly different interpretations of the word "share"). Rust also automatically deduces these traits where applicable, so most* things are thread-safe by default, and the language prevents you from using threads with thread-unsafe objects.

By the time you get to something that Rust considers thread-unsafe, there is rarely much opportunity to "just" fix it by switching implementations, as the problem likely involves some sort of inherently thread-unfriendly design (e.g. Cell or RefCell). RwLock is a bit like a thread-safe version of Cell/RefCell, but not really, because RwLock has stronger constraints on the caller (the caller must take care to avoid deadlock), and regardless, the API differs, so automatic deduction would be inappropriate. The exception is Rc/Arc, because the latter really is "just" a thread-safe implementation of the former, but a whole language rule for one special case probably wouldn't be worth it, especially since you might still need to wrap the refcounted object in a Mutex or something anyway (Arc doesn't protect the inner value from threads, it just protects its own reference count).

* The borrow checker already provides a measure of thread safety for "simple" objects, and the automatic deduction takes this into account, so a thread-unsafe object is generally going to be rather more complex than it would be in other languages. It's not like C where any static variable or shared pointer is automatically a data race waiting to happen. Rust lets you hand out immutable references like Halloween candy if you so choose, without putting thread safety at risk.


to post comments


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds