I have some memory:
let mut storage = [0u128; 256];
let storage_ref = &mut storage;
I want to make multiple copies of storage_ref, so that I can carefully mutate the u128
s within storage
, using cmpxchg16b in different threads. This will need to make use of unsafe
.
What is the syntax for making multiple copies of the storage_ref
(both pointer and size, to pass to the various threads)?
I have some memory:
let mut storage = [0u128; 256];
let storage_ref = &mut storage;
I want to make multiple copies of storage_ref, so that I can carefully mutate the u128
s within storage
, using cmpxchg16b in different threads. This will need to make use of unsafe
.
What is the syntax for making multiple copies of the storage_ref
(both pointer and size, to pass to the various threads)?
1 Answer
Reset to default 1To achieve this, you must convert the unique reference &mut [u128; 256]
into a raw pointer *mut [u128; 256]
, which can be done using a coercion:
let storage_ptr: *mut [u128; 256] = storage_ref;
Or, it can be done by constructing a raw pointer in the first place:
let storage_ptr: *mut [u128; 256] = &raw mut storage;
You must do this exactly once (not once per thread), and then you are free to distribute the pointer to many threads.
Since you intend to use atomic operations, you won’t be causing data races, which is necessary — data races are UB regardless of whether you use references or raw pointers. You do need to make sure to stop using the raw pointers before any other mutable reference is taken to storage
.
You should also consider, instead of using unsafe
and assembly code, using [std::sync::atomic::AtomicU128; 256]
, which allows atomic operations from safe code. (This type only exists on platforms which support 128-bit atomic operations, but that should work anywhere your assembly code would work.)
unsafe
blocks? – fadedbee Commented Feb 15 at 16:49[UnsafeCell<u128>; 256]
. You can extract mut pointer from a non-mut cell, so you'll have no problems with the borrow checker. – user4815162342 Commented Feb 15 at 18:27