简体   繁体   English

多线程安全计数器

[英]Multi-Thread Safe Counters

I want to make "count" thread safe in the following example. 在以下示例中,我想使“计数”线程安全。

In this, "process" is running constantly in a thread controlled in same class but "reset" is to be called by another thread through an object of the class. 在这种情况下,“进程”在同一个类中控制的线程中不断运行,但是另一个线程将通过该类的对象调用“重置”。

namespace sample
{
    class xyz
    {
        int count;

        reset()
        {
            count=0;
        }

        process()
        {
           ..
           ..
           ..
           count +=10
           ..
           ..
        }
    }
}

EDIT 1: Is this a possible solution? 编辑1:这可能解决方案吗?

public class Xyz
{
    private int count;

    private static Object loackable = new Object();

    public void Reset()
    {
        lock(lockable)
        {
            count = 0;
        }

    }

    public void Process()
    {
       lock(loackable)
       {            
           count += 10;
       }
    }
}

For basic counters you can use methods from. 对于基本计数器,可以使用from的方法。 Interlocked class. Interlocked班。

For anything more complicated wrap each operation on counter with lock using the same object to lock around single counter (either one static for all as you show in the question or instance objects as long as they paired to same counter all the time). 对于更复杂的事情,使用同一对象在单个带有计数器的lock对每个带有lock计数器进行包装(对于您在问题中显示的所有对象都是静态的,或者只要它们始终与同一计数器配对就可以实例对象)。

Note 注意

  • you need to protect both. 您需要同时保护两者。 Read and write operations if you need correct value. 如果需要正确的值,则进行读写操作。
  • volatile can't help you to implement counters in general case as += is not atomic operation and multiple threads can read same value and than increment it so for two threads incrementing counter by 10 you can get counter incremented by 10 or twenty depending on timing. volatile在一般情况下无法帮助您实现计数器,因为+=不是原子操作,并且多个线程可以读取相同的值,然后将其递增,因此对于两个线程,将计数器递增10,您可以根据时间将计数器递增10或二十。 It may work in case of single write thread giving impression that code is correct. 在单个写入线程给人以代码正确的印象的情况下,它可能会起作用。

You should add 'volatile' keyword for 'count' field. 您应该在“计数”字段中添加“易失性”关键字。 This ensure that the 'count' field will always be threading safe. 这样可以确保“ count”字段始终是线程安全的。 ( Read this ) 读这个

public class Xyz
{
    private volatile int count;

    public void Reset()
    {
        count = 0;
    }

    public void Process()
    {
        count += 10;
    }
}

And please, follow C# goodline ! 并且,请遵循C#goodline

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM