我需要一个int线程访问同步? [英] Do I need to synchronize thread access to an int?

查看:98
本文介绍了我需要一个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学习多线程++我被教导,你并不需要调用同步递增和递减操作,因为他们总是有一个汇编指令,因此是不可能的线程切换出呼叫中。是人教导我正确的,如果是这样,为什么不为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线程访问同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆