问题
I am new to .net and would like to know whether .net has the java equivalent of AtomicInteger, ConcurrentLinkedQueue, etc?
I did a bit of search and couldnt come up with anything.
The lock free algorithms need some sort of a CAS instruction, which is provided through the undocumented Unsafe class in Java, does .net have anything equivalent?
回答1:
In .NET there is the Interlocked class, with static methods Interlocked.Increment() and Interlocked.Decrement().
See http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx.
You will also find other atomic och synchronization constructs in the System.Threading namespace.
回答2:
I've written a good deal of lock free immutable collection structures in .Net. This includes, binary trees, maps, arrays, linked list, etc ... The source and binaries are available on code gallery
RantPack
回答3:
The Interlocked class has all the static methods needed to do simple atomic operations like increment, decrement, compare, swap, etc. Check out http://msdn.microsoft.com/en-us/library/system.threading.interlocked_members.aspx
For most collections you can get a synchronized collection through a static member called "Synchronized". Note however these aren't lock free constructs, they just hide the messiness of using locks/semaphores. Check the queue collection's synchronized method http://msdn.microsoft.com/en-us/library/system.collections.queue.synchronized.aspx
回答4:
For info, it is likely (here) that .NET 4.0 will inherit the CCR/TPL from Parallel Extensions. TPL, in particular, introduces a range of collections and other constructs designed for advanced threading scenarios (with minimal locks etc).
For now, there are a limited number of threaded collections etc, plus the usual locking primatives, plus Interlocked
, etc.
回答5:
Here is the problem I see with .net's Interlocked class.
I have multiple threads updating a counter. Each thread must get a unique value of the counter, thus no threads must get the same value.
The way the interlocked class in .net works, i have -
int counter;
void code(){
myThreadVal = Interlocked.increment(counter);
}
now since both threads can see the same value of the counter, they both can get the same value of myThreadVal.
However, in the case of java's AtomicInteger that would never happen, each thread would always get a different value.
来源:https://stackoverflow.com/questions/327358/lock-free-constructs-in-net