Hacker News new | ask | show | jobs
by randomskk 1796 days ago
That Raspberry Pi Pico code snippet is slightly unusual in that the `unsafe` there is because the library isn't sure that 1<<25 is a safe value to write to this register - for example, if the register was a DMA memory address pointer, it's not safe to allow directly writing arbitrary pointers to it since it would allow memory access outside of Rust's memory model. It's not to do with the potential atomicity requirement.

The exclusivity/atomicity in that case is ensured because the method is called on "p.SIO", an object that can't be accessed from both ISRs and the main code at the same time in safe Rust (because it doesn't "implement Sync"). If both an interrupt and the main thread need to access that peripheral, you need to provide some way of sharing it - either using `unsafe`, or in safe code by using a synchronisation primitive such as a critical-section based Mutex that provides that guarantee.

The book chapter you've linked to starts out by demonstrating what is essentially how you'd write this in C and thus requires unsafe, but it builds towards a safe solution - when using either the Atomic* variables (in the Atomic Access section) or mutexes (in the Mutex section), `unsafe` isn't required any more; the user's code is only safe Rust which provides synchronised access to the shared state between the main thread and the ISR.

In other words, the benefit over C is that it _is_ now possible to use only safe Rust to access memory and peripherals from both interrupts and the main thread, and that safe Rust is itself ensuring you can't cause race conditions. The unsafe option is there as a building block for those safe abstractions.

> So at the end of the day it's just C with different syntax, and a lot more hoopla. You've made everything mutable and unsafe.

Perhaps that chapter isn't getting the right message across then. The goal is to completely avoid applicaton code having to make things mutable and unsafe by providing the right abstractions that allow safe Rust to get the same work done while ensuring there are no races.