Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it threadsafe? I'm learing Threads and TheadSafe topic

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading