🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.arch
Article #68

Re: Optimization by programmers

#68
From: Dan Cross
Date: Mon, 12 Oct 2026 21:07
158 lines
7659 bytes
In article <1791830267-5857@newsgrouper.org>,
MitchAlsup  <user5857@newsgrouper.org.invalid> wrote:
>
>cross@spitfire.i.gajendra.net (Dan Cross) posted:
>
>First off: thank you dan for a well done explanation.
>
>> In article <1791742457-5857@newsgrouper.org>,
>> MitchAlsup  <user5857@newsgrouper.org.invalid> wrote:
>> >
>> >Terje Mathisen <terje.mathisen@tmsw.no> posted:
>> >
>> >> Dan Cross wrote:
>> >---------
>> >> 
>> >> My old asm/C brain _knows_ that a slice of something with a known 
>> >> address and total length is effectively the same thing as an unmutable 
>> >> array.
>> >
>> >Can I get a definition of what mutable in Rust means ??
>> 
>--------snip of what I understand clearly------------
>> 
>> So this will fail to compile:
>> 
>> ?	let mut foo = something();
>> ?	let foomut = &mut foo;	// Ok: only mutable
>> ?	let barmut = &mut foo	// Fail: a mut ref to foo exists
>
>Is this supposed to work across threads ?? so, only 1 thread has write
>access at any given point in time.

Yes, that's right.

>If so, how does one thread hand-off mutability to another ??

Typically, you use a mutual exclusion primitive of one kind or
another to serialize access to mutable state.  For example, the
standard library includes the usual complement of Mutex,
reader/writer locks, condition variables, barriers, reference
counters, thread-safe channels, and so on.  For bare-metal
programs we have to implement these ourselves, but there are
some third-party implementations that can help (for example, the
`spin` crate implements spinlocks, providing, an interface that
looks close to `std::sync::Mutex`).

Something I should have mentioned earlier is that Rust object
has a single, well-defined owner, and that references to that
object are borrowed _from the owner_.

So, using `Mutex` as an example, we make the `Mutex` itself the
owner of the object: the `.lock()` method lets threads borrow
mutable references to the object, and the serialization inherent
in the Mutex type and the locking protocol enforces the
"mut ^ immut" semantics across threads.

Similarly, a `RwLock` can hand out multiple immutable refs to
the object, but keeps track of them, and only lets one borrower
access a `mut ref` at a time, and only when there are no
outstanding immutable refs to it.

In fact, it's slightly more complex in that `mutex.lock()`
actually returns a proxy object that holds onto the reference;
its return type is actually, `LockResult<LockGuard<'_, T>>`,
where `'_` is an anonymous lifetime, and `T` is the type of the
thing protected by the `Mutex`.  `LockResult` lets someone
detect a lock that has been poisoned; the `LockGuard` is the
thing that holds the ref.  When it goes otu of scope, it
automatically unlocks the mutex, and it implements a trait
called `Deref` to forward uses on to the ref to the locked
object.

This all intersects with the `Send`/`Sync` stuff; `Mutex` is
`Sync`, and `Mutex` objects themselves are treated as immutable. 
So to share access to a `Foo` between threads, I use something
like a `Mutex<Foo>`.  This is an example of "Interior
Mutability", where something immutable (the `Mutex` object
itself) can hold onto something that is mutable.

This raises a question: if all this machinery is required for
safe access to shared data across threads anyway, then why all
the language-level rules?  The answer is hinted at by the mutex
object itself is immutable, we can hand out references to it
easily.  Since it owns the (mutable) object the lock protects,
it can decide how to hand out references to the object.

>--------------snip again--------
>> By default, all assignments in Rust have _move_ semantics: after
>> the assignment, the source is considered destroyed, and any
>> references to it are no longer valid.  That's why one can assign
>> to `foo` and on line 5 and then take a mut reference to it on
>> line 7; the assignment on 5 implicitly dropped the original
>> `foo` object created on line 1 and replaced it with a new
>> object, so the mut reference it created on line 3 is invalid;
>> an attempt to use it subsequently would fail to compile.
>
>This is clever.
> 
>> One can define a `copy` operator for types that should not have
>> move semantics; this is usually applied to trivial types (like
>> integers).
>> 
>> One may ask, "why bother with all of this stuff?" and the answer
>> is that Rust is designed for a multicore world.  There is one
>> other wrinkle here that gives Rust a lot of power, and that's
>> how all of this stuff interacts with data races: safe Rust code
>> is data race free.
>
>See question above.

See above; hopefully that helps?

There's one other thing here that may be interesting: how does
one implement any of this stuff _in Rust_?  In particular, how
does one implement interior mutability?

The answer is using something called the `UnsafeCell`:
https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html

`UnsafeCell` allows mutation of an object (the thing owned by
the cell) through a shared (what up to now I've been calling an
"immutable") reference to the cell.  It's the one place that
permits that behavior.

The implementatin of a spinlock in the `spin` crate is an
interesting read to understand the mechanics here:
https://codeberg.org/zesterer/spin/src/branch/master/src/mutex/spin.rs

>> Rust does not mandate a particular shape or type of (software)
>> thread, but because of the "mut ref ^ immut ref" rule, enforced
>> by the borrow checker at compile-time, safe Rust programs cannot
>> race on access to data, even in the face of multithreading.
>> 
>> Rust handles this by exposing two "marker traits", `Sync` and
>> `Send`. To quote the _Rustinomicon_, "A type is `Send` if it is
>> safe to send it to another thread" and "A type is `Sync` if it
>> is safe to share between threads (T is `Sync` if and only if
>> `&T` is `Send`)."  That is, a type can be _shared_ between
>> threads if it is safe to send an immutable reference to it from
>> one thread to another, and the compiler can check borrows
>> against the lifetimes of objects, hence, can detect data races
>> _statically, at compile time_.
>> (https://doc.rust-lang.org/nomicon/send-and-sync.html)
>> 
>> Those of us familiar with writing multithreaded programs will
>> recognize the power of these constructs: these rules, taken
>> together, statically eliminate entire categories of common
>> memory and concurrency problems.
>> 
>> Anyway, that what "mutable" means, in a nutshell, and why it is
>> important.
>
>Thanks again for a complete explanation.

Happy to do it.

	- Dan C.
Technical Details
Message-ID: <11aji7b$2fh$1@reader2.panix.com>
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!panix!.POSTED.spitfire.i.gajendra.net!not-for-mail
References: <1177fdi$26ea4$1@dont-email.me> <1791742457-5857@newsgrouper.org> <11aiv39$bpk$1@reader2.panix.com> <1791830267-5857@newsgrouper.org>

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!panix!.POSTED.spitfire.i.gajendra.net!not-for-mail
From: cross@spitfire.i.gajendra.net (Dan Cross)
Newsgroups: comp.arch
Subject: Re: Optimization by programmers
Date: Mon, 12 Oct 2026 21:07:55 -0000 (UTC)
Organization: PANIX Public Access Internet and UNIX, NYC
Message-ID: <11aji7b$2fh$1@reader2.panix.com>
References: <1177fdi$26ea4$1@dont-email.me> <1791742457-5857@newsgrouper.org> <11aiv39$bpk$1@reader2.panix.com> <1791830267-5857@newsgrouper.org>
Injection-Date: Mon, 12 Oct 2026 21:07:55 -0000 (UTC)
Injection-Info: reader2.panix.com; posting-host="spitfire.i.gajendra.net:166.84.136.80";
	logging-data="2545"; mail-complaints-to="abuse@panix.com"
X-Newsreader: trn 4.0-test77 (Sep 1, 2010)
Originator: cross@spitfire.i.gajendra.net (Dan Cross)