21

Interlocked.Increment seems like among the most standard/simple of operations one would need to perform in multithreaded code.

I assume that the functionality of the method is some sort pattern that anyone with threading experience would be able to replicate.

So basically what I am wondering is if someone could provide an exact duplicate (with explanation of how it works) of what the Interlocked.Increment method is actually doing internally? (I have looked for the source of the actual method but been unable to find it)

4

3 に答える 3

14

アルバハリ氏によると、それは2つのことをします:

  • 操作のアトミック性をOSとVMに認識させるため、たとえば32ビットシステムでの64ビット値の操作はアトミックになります
  • full fenceインターロックされた変数の制限付きの並べ替えとキャッシュを生成します

そのリンクを見てください-それはいくつかの良い例を与えます。

于 2011-04-18T08:20:51.353 に答える
9

これは実装の詳細だと思いますが、それを確認する1つの方法は、JITでコンパイルされたコードを調べることです。次のサンプルについて考えてみます。

private static int Value = 42;
public static void Foo() {
   Interlocked.Increment(ref Value);
}

x86では、次のように生成されます

lock inc dword <LOCATION>

ロック修飾子はバスをロックして、複数のCPUが同じデータ位置を更新しないようにします。

x64では生成されます

lock xadd dword ptr <LOCATION>,eax
于 2011-04-18T08:35:16.993 に答える
1

I would expect it to be a wrapper to the InterlockedIncrement64 Win32 API call.


EDIT: I see that it was a very short response. Building a little on it: It is easy to replicate the functionality of the function, but not the performance. There are native instructions in most CPUs that provide you with the atomic "Interlocked exchange and add" instruction, so you want that instruction to be used to implement your function, and I expect that the easiest way to achieve that from within C# would be to make the win32 API call. For more background on the subject, have a look at this whitepaper.

于 2011-04-18T08:12:30.870 に答える