P
Pierre
Using the "volatile" keyword, creates a problem if I intend to use any of
the interlocked APIs. The compiler generates an error if I use the following
line, for example:
Interlocked.Increment(ref count);
The error says that a volatile field cannot be used as ref or out, but if I
don't use the volatile field, the value may be cached away in some method
that is just reading the field.
Consider, for example, an integer field being used by three threads. Two
threads intend to increment the value of the field while the third one just
wishes to check the value. Consider, for example, the initial value of the
field is 5.
If both the writer threads increment the value using the interlocked API,
the final value of the field is guaranteed to be 7. Without the use of the
interlocked API, the final value could be 6. Therefore, using the
interlocked API is a must in this case.
Without the field being marked as volatile, the reader thread may always see
the value as 5.
As can be seen, we need both the mechanisms under some cases.
What might be the solution for such situations?
the interlocked APIs. The compiler generates an error if I use the following
line, for example:
Interlocked.Increment(ref count);
The error says that a volatile field cannot be used as ref or out, but if I
don't use the volatile field, the value may be cached away in some method
that is just reading the field.
Consider, for example, an integer field being used by three threads. Two
threads intend to increment the value of the field while the third one just
wishes to check the value. Consider, for example, the initial value of the
field is 5.
If both the writer threads increment the value using the interlocked API,
the final value of the field is guaranteed to be 7. Without the use of the
interlocked API, the final value could be 6. Therefore, using the
interlocked API is a must in this case.
Without the field being marked as volatile, the reader thread may always see
the value as 5.
As can be seen, we need both the mechanisms under some cases.
What might be the solution for such situations?