@Pop Catalin: I'm not ok with what you said in :
If the structure is intended to be thread safe, then the methods should be made instance methods only if they do atomic operations, else static methods should be chosen.
Here is a small program that demonstrate that static methods don't solve this problem for structs :
using System;
using System.Threading;
using System.Diagnostics;
namespace ThreadTest
{
class Program
{
struct SmallMatrix
{
double m_a, m_b, m_c, m_d;
public SmallMatrix(double x)
{
m_a = x;
m_b = x;
m_c = x;
m_d = x;
}
public static bool SameValueEverywhere(SmallMatrix m)
{
return (m.m_a == m.m_b)
&& (m.m_a == m.m_c)
&& (m.m_a == m.m_d);
}
}
static SmallMatrix s_smallMatrix;
static void Watcher()
{
while (true)
Debug.Assert(SmallMatrix.SameValueEverywhere(s_smallMatrix));
}
static void Main(string[] args)
{
(new Thread(Watcher)).Start();
while (true)
{
s_smallMatrix = new SmallMatrix(0);
s_smallMatrix = new SmallMatrix(1);
}
}
}
}
Note that this behavior can't be observed with double values on common processor as most x86 instructions have a version working with 64bits chunks such as movl
.
So thread safety doesn't seem a good reason for IsNaN to be static :
- The framework should be platform agnostic and so it shouldn't presuppose things like the processor architecture. IsNaN thread-safety is dependent on the fact that 64bits values are always accessed and modified atomicaly on the target architecture (And Compact framework targets aren't x86...).
- IsNaN is useless by itself and in a context where multiple thread could access
someVar
this code is anyway unsafe (regardless of the thread safety of IsNaN) :
print("code sample");
if (!double.IsNaN(someVar))
Console.WriteLine(someVar);
What i mean is that even if IsNaN is implemented by doing ==
comparisons with all possible NaN values... (not really possible)
...who care that the value evolve during the execution of the method if anyway it could have changed once the method terminate... or it could even be an intermediate value that should never have been here if the target architecture isn't x86...
Accessing intristic values in two different threads is NOT safe in general so i see no interest in providing some illusion of safety by putting any method static when dealing with structs or any other type,