paulirwin commented on issue #1063:
URL: https://github.com/apache/lucenenet/issues/1063#issuecomment-2526563445

   > Actually, no, that would not work. `Interlocked` operations require a 
stable memory location to work on unless we use unsafe code or pinning, which 
introduces complexity and potential risks.
   > 
   > Per ChatGPT:
   > ## Structs and Atomic Operations
   > 
   > If you make your type a struct, using `Interlocked` to manipulate its 
internal `Value` field directly would not work as intended for the following 
reasons:
   > 
   >     1. Copy Semantics:
   >        
   >        * Structs are value types, so when you access or modify them, you 
typically operate on a **copy**. This would break thread safety and atomicity 
because each thread could be working with independent copies of the struct.
   > 
   >     2. Interlocked Requires References:
   >        
   >        * The `Interlocked` class operates on references to shared memory 
locations. For example, `Interlocked.Exchange` and 
`Interlocked.CompareExchange` require a `ref` to the field being modified. 
Structs cannot provide such a reference to a field within themselves.
   > 
   >     3. Struct Field Pinning:
   >        
   >        * Even with unsafe code, it is challenging to guarantee safe and 
correct atomic operations on a field of a struct because the struct might be 
moved or copied by the runtime, breaking assumptions about its memory location.
   
   ChatGPT is hallucinating a bit here, as it did for me before I asked the 
question. GPT-4o said to me that structs' values are copied atomically (wrong) 
and that you can solve the problem of atomically accessing a long by making the 
long field `volatile` (wrong again). 🙄 
   
   You absolutely can use struct fields as `ref` arguments to Interlocked; I 
just confirmed this with a test. And a struct is even more stable of a memory 
location than a value in a class on the heap. It's closer to the original 
`long` field in terms of memory location. No pinning or unsafe code required.
   
   The only thing we'd have to be careful about is to not pass the struct by 
value which would non-atomically copy the long field, but given that it's a 
field already we should be fine here (just need to not have any methods in the 
class that take a `ValueAtomicInt64` and pass the field to it unless if with 
`ref`, for example). We'd also have to look out for any naïve clones and ensure 
that we're properly atomically retrieving the long value and setting a new 
atomic struct value in the new clone. But this would allow us to not add extra 
allocations for this case.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: dev-unsubscr...@lucenenet.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to