I (more or less) know what is ThreadSafe, but I don’t know how to recognize the ThreadSafe way.
using Tests;
int a = 2;
new Thread(() =>
{
a = 3;
}).Start();
for (; ; )
{
Console.WriteLine(a);
Thread.Sleep(200);
}
I think that it’s not TheadSafe but… why?
I expect simple answer about ThreadSafe
>Solution :
It depends on what you mean with threadsafe. Will it crash? no. Will it eventually print "3"? Probably, but it is not guaranteed by the language. The compiler and CPU does not have to take other threads into account when optimizing unless there is some explicit synchronization. In practice not all possible optimizations are performed, and x86 CPUs provide a stronger memory model than .Net guarantees, but that does not mean you should rely on these factors.
The easy way to ensure it is safe is to use locking:
int a = 2;
var lockObj = new object();
new Thread(() =>
{
lock(lockObj){
a = 3;
}
}).Start();
for (; ; )
{
lock(lockObj){
Console.WriteLine(a);
}
Thread.Sleep(200);
}
For such a simple case an alternative could be volatile or memory barriers, but these are more difficult to use correctly. So if you are starting out I would recommend using locks whenever there is the possibility of concurrent reads and writes.