VB.NET, shared sub question

Soldato
Joined
18 Oct 2002
Posts
15,861
Location
NW London
Hi,

I have a created a class, which contains a sub routine.

This sub routine, should ideally be accessable by objects which are not members of the class, so I would like to make the sub, a 'shared sub' (call it Sub1).

Question: I am using many threads and there will be possibly 100s of 1000s of threads all wanting to use Sub1 (which is at present, is not shared).

At present Sub1 , is not a shared sub, so every time a thread wishes to use Sub1 , I am creating a (dummy) instance of the class and then applying Sub1, to that instance.

My program works flawlessly using the above technique.

Question: If I were to turn Sub1 (which is not currently shared) into a shared sub, and directly had various threads calling Sub1, would there be any issues with locking, ie. would it possible for 2 threads to enter that thread and start overwriting variables, which another thread has written to?

NOTE: there are no shared variables/properties in Sub1 and all variables used in Sub1 are declared within the sub itself.


Thanks
 
Local arguments and variables are allocated on the stack of the executing thread, so you will not create any race conditions on those.

There is possible exception though. You can explicitly declare a local variable as "static" in your methods. Static variables in shared methods are shared, static variables in instance methods are instance variables. But that's kind of an exotic feature on the language you'll most likely never see in use. It's almost always better to declare them on class level when you need that kind of behavior.
 
Last edited:
Hi Goofball. Thanks for your answer.
I actually had this question answered a few minutes ago in another forum.

For anybody wanting to know the answer to this, here it is:

http://www.vbforums.com/showthread.php?p=3877075#post3877075

The two threads will execute the same code. They will cover the same instructions. However, each one will keep its own set of local variables. When thread A is given time on the processor, it loads all of its variables into the processor registers, and performs operations
until it is time to give up the processor to another thread, at which time it takes all of the data it is working on, and stores it back to its own special memory area. So two threads can work with the same sequence of instructions, but each will be using only its own data.

In a nutshell, 2 threads will not enter the same sub and process eachother's variables. In effect...the above code is thread safe, providing we passing variables ByVal. Obviously, if we are passing references, then we need to use ReaderWriterLockSlim to prevent 2 threads from operating on the same object/variable, at the same time.
 
Back
Top Bottom