Reputation: 97
I've seen the following suggestion for doing pointer arithmetic all over the net:
IntPtr ptr = new IntPtr(oldptr.ToInt64() + 2);
Is that really thread safe? I guess not since the ToInt64
and addition is not atomic. Is that the reason for the new IntPtr.Add()
function in .NET4?
http://msdn.microsoft.com/en-us/library/system.intptr.add.aspx
After reading up on the thread safety based on your great comments, I think I can clarify my question. My concern is that the Garbage Collector might move the pointer from the time I get the value of it with ToInt64()
and the new IntPtr
is created. So, my question is rather:
ToInt64()
or ToInt32()
will return "A 64-bit/32-bit signed integer equal to the value of this instance." (MSDN). I guess this value is the real address (pointer) to the data. I suppose this value will not be updated accordingly if the GC happen to move the data. So creating a new IntPtr based on this value can possibly point to the wrong place. I guess you must use fixed / pinned pointer to prevent this.
Upvotes: 2
Views: 393
Reputation: 613432
By threadsafe I suppose that you are concerned with the race condition associated with multiple threads performing read-modify-write cycles on the same variable. That's not what you have in your code in the question. It's not obvious what threading problems you anticipate with that code.
Perhaps the example you meant to use was this:
IntPtr ptr = ...;
...
ptr = (IntPtr) (ptr.ToInt64() + 2);
Now, that code is not threadsafe. If multiple threads execute the read-modify-write at the same time, you have the classic data race.
However, the new IntPtr.Add
method is not threadsafe either. Nor are the new addition operators. By which I mean to say that ptr += 2
is not threadsafe, for example.
You'd need a lock, or the Interlocked
class to implement threadsafe incrementing.
Upvotes: 4
Reputation: 14736
Is that the reason for the new IntPtr.Add() function in .NET4?
Only speculation but a more likely reason is:
Languages that do not support operator overloading or custom operators can use this method to add an offset to the value of a pointer."
Upvotes: 1