pub unsafe fn write_volatile<O, T>(dst: BitPtr<Mut, O, T>, value: bool) where
    O: BitOrder,
    T: BitStore
Expand description

Performs a volatile write of a memory location with the given bit.

Because processors do not have single-bit write instructions, this must perform a volatile read of the location, perform the bit modification within the processor register, then perform a volatile write back to memory. These three steps are guaranteed to be atomic.

Volatile operations are intended to act on I/O memory, and are guaranteed not to be elided or reördered by the compiler across other volatile operations.

Original

ptr::write_volatile

Notes

Rust does not curretnly have a rigorously and formally defined memory model, so the precise semantics of what “volatile” means here is subject to change over time. That being said, the semantics will almost always end up pretty similar to C11’s definition of volatile.

The compiler shouldn’t change the relative order or number of volatile memory operations.

Safety

Behavior is undefined if any of the following conditions are violated:

  • dst must be valid for writes
  • no other pointer must race dst to view or modify the referent location unless T is capable of ensuring race safety.

Just like in C, whether an operation is volatile has no bearing whatsoëver on questions involving concurrent access from multiple threads. Volatile accesses behave exactly like non-atomic accesses in that regard. In particular, a race between a write_volatile and any other operation (reading or writing) on the same location is undefined behavior.

This is true even for atomic types! This instruction is an ordinary store that the compiler will not remove. It is not an atomic instruction.

Examples

use bitvec::prelude::*;

let mut data = 0u8;
let ptr = BitPtr::<_, Lsb0, _>::from_mut(&mut data);
unsafe {
  bitvec::ptr::write_volatile(ptr, true);
  assert!(bitvec::ptr::read_volatile(ptr.immut()));
}