简体   繁体   中英

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?

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. Interlocked class.

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).

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. 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. ( Read this )

public class Xyz
{
    private volatile int count;

    public void Reset()
    {
        count = 0;
    }

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

And please, follow C# goodline !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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