我需要同步线程访问一个int

我需要同步线程访问一个int

本文介绍了我需要同步线程访问一个int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚写了一个由多个线程同时调用的方法,我需要跟踪所有线程何时完成。代码使用此模式:

I've just written a method that is called by multiple threads simultaneously and I need to keep track of when all the threads have completed. The code uses this pattern:

private void RunReport()
{
   _reportsRunning++;

   try
   {
       //code to run the report
   }
   finally
   {
       _reportsRunning--;
   }
}

这是代码中唯一的 _reportsRunning 的值已更改,该方法需要大约一秒钟才能运行。

This is the only place within the code that _reportsRunning's value is changed, and the method takes about a second to run.

有时候,或者线程运行报告在一起的_reportsRunning的最终结果可以下降到-1。如果我在一个锁中包装对 _runningReports ++ _runningReports - 的调用,那么行为看起来是正确和一致的。

Occasionally when I have more than six or so threads running reports together the final result for _reportsRunning can get down to -1. If I wrap the calls to _runningReports++ and _runningReports-- in a lock then the behaviour appears to be correct and consistent.

所以,对于这个问题:当我在C ++学习多线程时,我被教导你不需要同步调用递增和递减操作,因为它们总是一个汇编指令,因此线程不可能在调用中断。

So, to the question: When I was learning multithreading in C++ I was taught that you didn't need to synchronize calls to increment and decrement operations because they were always one assembly instruction and therefore it was impossible for the thread to be switched out mid-call. Was I taught correctly, and if so, how come that doesn't hold true for C#?

推荐答案

A ++ 运算符在C#中不是原子的(我怀疑它在C ++中是原子的)所以是的,你的计数受种族条件的制约。

A ++ operator is not atomic in C# (and I doubt it is guaranteed to be atomic in C++) so yes, your counting is subject to race conditions.

使用Interlocked.Increment和.Decrement

Use Interlocked.Increment and .Decrement

System.Threading.Interlocked.Increment(ref _reportsRunning);
try
{
  ...
}
finally
{
   System.Threading.Interlocked.Decrement(ref _reportsRunning);
}

这篇关于我需要同步线程访问一个int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:27