Editorials

Dot Net Interlocked

Dot Net Interlocked
I continue to be affirmed that the ability to code multi-threaded applications is an essential skill for developers today. Most computers ship with multiple cores. Even tablets and phones are shipping with multiple cores or CPUs. Your app has increased benefit when it is capable of running multiple threads.

There are times when you wish to share data in a fashion that may be manipulated by multiple threads. Say you have a counter variable managed by your main thread. Other multiple threads are executing, which increment the counter as they complete. Even if the incrementing is done by calling a method in the main thread code, the fact that the incrementing is done by multiple concurrent threads can cause unexpected results.

The problem is that of timing. Here is a sequence from a CPU standpoint…

  1. Get memory and insert into register
  2. Increment register
  3. Write register to memory

There is nothing that says the process may not be interrupted between any of those three steps. If that happens, and another thread executing the same task occurs, when it starts it will get the same value out of memory as the previous thread, because the increment has not yet been written to memory.

One answer is to use locking so that no two threads may simultaneously manipulate the counter. Locking resolves this issue, but is a lot of work to code and the implementation is heavy.

The Interlocked class in dot net solves this issue elegantly. Using the Interlocked class there are a number of methods you can execute, which are all guaranteed to be atomic (all tasks necessary to complete the method must execute before any other thread may execute the same).

Take a look at the Interlocked class in dot net and see of the methods there work for you in your situation.

Cheers,

Ben

$$SWYNK$$

Featured Article(s)
Old wine in new bottles: cloud computing
The technology of the cloud is not new. How the technology is being exploited is new. Read on to see how the old technology is being harnessed in new ways.

Featured White Paper(s)
Encryption Key Management Simplified
Managing encryption keys is a fundamental step to securing encrypted data, meeting compliance requirements, and preventing da… (read more)

Featured Script
Genearete Grants
This script helps in creating a .sql file with INSERT,DELETE,UPDATE,SELECT grants on all tables in a db to users of your choi… (read more)