Interlocked.CompareExchange on Nullable<int> #114550
-
This has come up a few times in our codebase where we would really want CompareExchange on Nullable to work. Most of the interlocked operations are not possible, but an Interlocked.Read, Interlocked.Exchange, and Interlocked.CompareExchange are possible. An Interlocked.Write here would also be very useful but there's scarcely any precedent for that. (We took a dependency on writing to a long is atomic on 64 bit). But if there's only going to be one, CompareExchange is definitely it. I could not check if it's possibly simply because I could not check if Nullable actually has 8 byte alignment or not. If the alignment is there, the feasibility is quite reasonable. It's mostly a problem of hammering this past the compiler:
So what's the big idea? We already have CompareExchange on a long; no reason to write the implementation twice. Fragment from our internal discussion on the most recent case:
lazy is far too heavyweight for the insanely rare case; and calling it twice is harmless just slow. This is just one example far from being enough by itself. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
8-bytes alignment is not guaranteed for |
Beta Was this translation helpful? Give feedback.
-
In which case I definitely can't provide my own implementation because it would it wouldn't work on x64 either. It would run but not actually be atomic because that is the penalty. I could however use the union trick, which doesn't package up neatly into an API. |
Beta Was this translation helpful? Give feedback.
In which case I definitely can't provide my own implementation because it would it wouldn't work on x64 either. It would run but not actually be atomic because that is the penalty.
I could however use the union trick, which doesn't package up neatly into an API.