Lock free constructs in .net

最后都变了- 提交于 2019-12-04 08:38:10

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.

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

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!