R
rob
Hi,
I am trying gain a deeper understanding of volatile in C# and I am
hoping someone can offer some clarity on a hypothetical example I am
thinking though.
Say I have an external application (db, socket program, whatever) that
I want to use to manage thread synchronization in my C# program. So
instead of using lock(), I want will call an external application to
get logical mutex, then do synchronized work in my program, then call
the external app to release the mutex. The synchronization is being
used to protect a string[] array so that only one thread is accessing
it at a time.
Is this program thread safe?
I am fairly certain that if I was protecting a ‘volatile string’ (and
not an array) the program would be thread safe since the volatile
keyword ensures proper execution order. Also, I have read that without
volatile, it is possible that optimizations could cause two threads to
have different views of the data due to register caching techniques by
the compiler and hardware. If I declare my string[] array as volatile,
I think that only the array reference is treated as volatile and not
its elements. I don’t believe there is a way to declare elements of an
array as volatile, but I don’t know if this is because it is
unnecessary or if the language’s memory model is not powerful enough
to support it?
Thanks,
Rob
I am trying gain a deeper understanding of volatile in C# and I am
hoping someone can offer some clarity on a hypothetical example I am
thinking though.
Say I have an external application (db, socket program, whatever) that
I want to use to manage thread synchronization in my C# program. So
instead of using lock(), I want will call an external application to
get logical mutex, then do synchronized work in my program, then call
the external app to release the mutex. The synchronization is being
used to protect a string[] array so that only one thread is accessing
it at a time.
Is this program thread safe?
I am fairly certain that if I was protecting a ‘volatile string’ (and
not an array) the program would be thread safe since the volatile
keyword ensures proper execution order. Also, I have read that without
volatile, it is possible that optimizations could cause two threads to
have different views of the data due to register caching techniques by
the compiler and hardware. If I declare my string[] array as volatile,
I think that only the array reference is treated as volatile and not
its elements. I don’t believe there is a way to declare elements of an
array as volatile, but I don’t know if this is because it is
unnecessary or if the language’s memory model is not powerful enough
to support it?
Thanks,
Rob