multithreading and static/class variable

  • Thread starter Thread starter Peter K
  • Start date Start date
P

Peter K

Hi

an application I am working on has a class with a static class variable
"LastIndex" which various (static) methods in the class can set.

The idea is that callers of this class can see the "last valid index" after
various method calls.

But this class is used in a multithreaded application, and I am sure that
this will cause confusion as it could be possible that multiple threads
could execute methods in the class, updating LastIndex - so none of the
multiple threads really know what "their" last index is. Is that a correct
appraisal?

Assuming my understanding is correct, how could I fix this? Is it possible
to have a "thread static variable" in the class? Then there is actually a
new copy of this class variable per thread which uses the class... so each
thread knows its own "last index".

Thanks,
Peter
 
Peter K said:
[...] Is it possible
to have a "thread static variable" in the class?

Yes, you apply to it the attribute [ThreadStatic]:

[ThreadStatic] static int LastIndex;
 
No,

you can synchronize access to LastIndex for example with lock operator.

There are several thread synchronization techniques described in MSDN and in
other places.
 
That's not exactly what the OP is looking for. In this case, a lock is
not going to help, as he wants each thread to have its own copy of the
variable. Alberto's suggestion is the right one for this particular case,
using the ThreadStatic attribute.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top