should I *always* synchronize access to all double field/property/variables that used from more than one thread?

前提是你 提交于 2019-12-05 12:21:49

Yes, you need to do something. double and decimal are not guaranteed to be atomic, so if you don't protect it you could get a torn value - i.e. your first bullet is entirely correct.

Re volatile; it is moot; you are not allowed to have a volatile field that is double or decimal, so the simplest answer is: lock.

Getting double to fail is a royal PITA; but here's a torn-value example featuring decimal (note the numbers of success/fail will change each iteration, even though the data is the same; this is the randomness of thread scheduling):

using System;
using System.Threading;
static class Program
{
    private static decimal shared ;
    static void Main()
    {
        Random random = new Random(12345);
        decimal[] values = new decimal[20];
        Console.WriteLine("Values:");
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = (decimal)random.NextDouble();
            Console.WriteLine(values[i]);
        }
        Console.WriteLine();
        object allAtOnce = new object();
        int waiting = 10;
        shared = values[0];
        int correct = 0, fail = 0;
        for(int i = 0 ; i < 10 ; i++)
        {
            Thread thread = new Thread(() =>
            {
                lock(allAtOnce)
                {
                    if (Interlocked.Decrement(ref waiting) == 0)
                    {
                        Monitor.PulseAll(allAtOnce);
                    } else
                    {
                        Monitor.Wait(allAtOnce);
                    }
                }
                for(int j = 0 ; j < 1000 ; j++)
                {
                    for(int k = 0 ; k < values.Length ; k++)
                    {
                        Thread.MemoryBarrier();
                        var tmp = shared;
                        if(Array.IndexOf(values, tmp) < 0)
                        {
                            Console.WriteLine("Invalid value detected: " + tmp);
                            Interlocked.Increment(ref fail);
                        } else
                        {
                            Interlocked.Increment(ref correct);
                        }
                        shared = values[k];
                    }
                }
                if (Interlocked.Increment(ref waiting) == 10)
                {
                    Console.WriteLine("{0} correct, {1} fails",
                        Interlocked.CompareExchange(ref correct, 0, 0),
                        Interlocked.CompareExchange(ref fail, 0, 0));
                    Console.WriteLine("All done; press any key");
                    Console.ReadKey();
                }
            });
            thread.IsBackground = false;
            thread.Start();
        }
    }
}

The key point; the language makes no guarantees for the atomicity of double. In reality, I expect you'll be fine, but most subtle problems caused by threading are due to using "I expect" instead of "I can guarantee".

If you want to guarantee that a block of code will be executed and finished before another thread manipulates it, surround that block of code with a lock.

You may be lucky, and threads may never battle over using a variable, but to make sure that it never happens, making sure precautions are taken wouldn't hurt.

Take a look here - this might help: http://msdn.microsoft.com/en-us/library/ms173179%28v=vs.80%29.aspx

a general answer would be - updates should be synchronized for all "shared" variables. For exact answer need to see the code snippet.

Yes, you need to lock to be sure you get the correct result if multiple threads read/write a double at the same time.

Here's a failing example

[TestFixture]
public class DoubleTest
{
    private double theDouble;

    [Test]
    public void ShouldFailCalledParallell()
    {
        theDouble = 0;
        const int noOfTasks = 100;
        const int noOfLoopInTask = 100;
        var tasks = new Task[noOfTasks];
        for (var i = 0; i < noOfTasks; i++)
        {
            tasks[i] = new Task(() =>
                                    {
                                        for (var j = 0; j < noOfLoopInTask; j++)
                                        {
                                            theDouble++;
                                        }
                                    });
        }
        foreach (var task in tasks)
        {
            task.Start();
        }
        Task.WaitAll(tasks);
        theDouble.Should().Be.EqualTo(noOfTasks * noOfLoopInTask);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!