Is it safe to access this variable from multiple threads?

I usually write code that follows these lines:

public class MyClass { static bool m_stop = false; public static void Main() { var th = new Thread(DoStuff); th.Start(); Console.ReadLine(); m_stop = true; th.Join(); } private static void DoStuff() { while( !m_stop ) { // do things here } } } 

... and I always synchronize access to the m_stop variable, just out of habit. I'm wondering if this needs to be done (assuming that doing an extra loop or two in DoStuff () doesn't hurt anything). What's the worst thing that can happen if the code runs that way? I played with the thought of using the volatile keyword for m_stop, but I'm not sure even that is necessary. Does anyone know for sure?

+1
source share
3 answers

Without being volatile and without any kind of synchronization, the code you showed is not thread safe. One thread can change the value of a variable, and another thread will never see it, looping forever. If you synchronize all access to it using a shared lock, this is thread safe.

Now volatility is a complex topic - I thought I understood it until recently, but it doesnโ€™t mean that I thought it did , However, Iโ€™m sure that just changing the volatile variable will do what you need.

For something more complicated, I usually use full synchronization: take out the lock every time you access shared data.

+4
source

Although there is nothing technically wrong with this approach, you may run into problems when your application needs to scale. Also, you do not need to do m_stop volatile if you synchronize access with it.

+1
source

you must put a memory barrier when updating m_stop. so you have to mark it as volatile (or put memory locks / volatile reads - write yourself)

0
source

Source: https://habr.com/ru/post/919364/


All Articles