Using volatile for one-way communication between threads in .NET.

I read quite a few posts on this subject, and I think I finally understood how the volatile keyword works in C #. However, I wanted to ask here to make sure that I understand the concepts correctly. Consider the following code:

 class ThreadWrapper { public bool Enabled { get; set; } private void ThreadMethod() { while (Enabled) { // ... Do work } } } 

From what I understand, if another thread had to set Enabled=false , the original thread might not see this change right away (or maybe someday?). To ensure that the compiler does not optimize access to the Enabled property and relies on cached values, changing the code as follows should fix the situation.

  public bool Enabled { get {return mEnabled;} set {mEnabled=value;} } private volatile bool mEnabled; 

Now that the Enabled value is read, it is guaranteed to get its most current value, right? If so, I should be able to use it as a simple signal or flag (for example, I am above).

As another example, consider the following:

 class C { private volatile int i; private volatile bool enabledA; private volatile bool enabledB; void ThreadA() { i = 0; // Reset counter while (enabledA) { // .. Do some other repeated work if (i > 100) { // .. Handle threshold case } } } void ThreadB() { while (enabledB) { // .. Do work if (condition) // Some condition occurs that we want to count { i++; } } } } 

For simple cross-threading, for example, is volatile satisfactory here? I understand that i++ not an atomic operation, but if one thread does all the increment and the other just wants to read it to see if it reaches a certain threshold, are we okay?

Edit: Of course, I found another similar question with detailed answers after the fact.

+6
source share
2 answers

Yes, this should be safe and is one of the intended uses of the volatile keyword. Please note, however, that you should not focus only on checking the condition; if you just want to wait until it changes, use the correct synchronization primitive to avoid wasting processor time. Also note that this method only works because you have only one thread record; if several threads try to increase the counter, you may lose the counter (because read-change-write is not atomic).

+3
source

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


All Articles