0

I have a static variable which is accessed by multiple threads in multiple object. The problem is if I set value in one thread it does not reflect in another thread. To resolve the issue I made the variable thread static but still the value changed in one thread does to reflect in another thread. That’s how I declared the variable:

[ThreadStatic]
public static string ThreadVar;

Any suggestion on how to resolve the issue?

user2692032
  • 771
  • 7
  • 26
  • 4
    ThreadStatic makes quite an opposite - http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(v=vs.110).aspx. Each thread will access its own variable. – Eugene Podskal Jul 28 '14 at 14:45
  • possible duplicate of [How to make a static variable thread-safe](http://stackoverflow.com/questions/12981190/how-to-make-a-static-variable-thread-safe) – Eugene Podskal Jul 28 '14 at 14:48
  • You will need to use some locking to make sure only one thread access it at a time. Look at a readerwriterlock http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock(v=vs.110).aspx – Mike Norgate Jul 28 '14 at 14:48
  • @MikeNorgate Reading from and writing to references is guaranteed to be atomic, and since `string` is immutable, it does not appear that locking is required in this case. (That's not to say that the OP is not doing something thread-unsafe, only that locking isn't always necessary.) – cdhowie Jul 28 '14 at 15:03
  • @cdhowie I did not know that. Can you send me a link with some more information on that – Mike Norgate Jul 28 '14 at 15:06
  • @MikeNorgate [C# language spec §5.5](http://msdn.microsoft.com/en-us/library/aa691278(v=vs.71).aspx): *"Reads and writes of the following data types are atomic: ... and reference types."* – cdhowie Jul 28 '14 at 15:10

1 Answers1

4

The compiler and JIT are free to assume that fields will not be changed by multiple threads, and can optimize away re-fetches of the same field if it is provable that the value cannot be changed by the current thread between fetches.

Marking the field volatile communicates the opposite: that you expect the field to be changed by external forces (including other threads) and that the compiler/JIT must not optimize away any re-fetches.

Note that marking the field volatile does not immediately mean that all usage of the field is thread-safe, it only means that one thread will notice when a new value is written to the field by another thread. We would need to see more of your code to determine if there is a thread safety issue.

[ThreadStatic], in comparison, tells the compiler that each thread should have its own copy of the variable, which based on your question is not at all what you want.

cdhowie
  • 158,093
  • 24
  • 286
  • 300