0

Assume I have shared double variable. Thread A updates it several thousands times per second. In another thread B I want to be notified somehow about "update" every time this happens.

I was tried to avoid notifications completely and just use while(true) loop but this introduced significant slowdowns into my program lock-free calc: how to sum N double numbers that are changing by other threads? probably because of that "Meanwhile you keep on loading that same array from memory over and over which is not really good for performance since memory bandwith is limited."

I've also tried using Monitor class but it was also pretty slow and I've seen up to 1-2 ms delays when Monitor.TryEnter return false.

I now think that I need to do notifications using lock-free technique, probably using SpinLock or something else?

Community
  • 1
  • 1
Oleg Vazhnev
  • 23,239
  • 54
  • 171
  • 305

2 Answers2

3

Use wait handle to notify between threads

    System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false);
    double d = 0;
    public void ThreadA(object state)
    {
        while (true)
        {
            d++;
            are.Set();
        }
    }

    public void ThreadB(object state)
    {
        while (true)
        {
            are.WaitOne();
            double current = d;
        }
    }
Waqar
  • 2,511
  • 18
  • 15
  • i like that but the question is how much overhead `AutoResetEvent` introduce. – Oleg Vazhnev Jul 09 '12 at 13:31
  • i didn't test this. You can test the chunk of code for 1000 iteration and check the time taken to execute these iterations then check same iterations with lock. then you can know the results. – Waqar Jul 09 '12 at 14:37
0

Don't keep the notified thread on all the time. When thread A changes the value, he should notify thread B and move on.

Amiram Korach
  • 13,056
  • 3
  • 28
  • 30