On 28 Sep 2005 23:36:53 -0700,
(E-Mail Removed) wrote:
>Hi,
>
>I read some pages from the link given, but I am note sure if I
>understood well.
>
>If I have a method that is called twice using two different threads
>
>private void myMethod() {......}
>
>Thread t1 = new Thread(new ThreadStart(myMethod);
>Thread t2 = new Thread(new ThreadStart(myMethod);
>t1.Start(); t2.Start();
>
>If I'm correct, threads share memory. This applies for global
>variables. In case of method class, should the two threads calling the
>same method that I created conflict with each other, even if they are
>accessing no global variables?
If two threads access the same memory on the Heap at the same time a
memory conflict can occur. (Note: Problems usually only occur if
atleast one thread are changing values on the Heap)
So what is on the Heap?
* Each object instance has space reserved for it on the heap. This
space contains all instance variables. (Note: If the variable is of a
reference type it simply contains a memory pointer that points to
another place on the heap.
* Each class also has space reserved for it on the heap. This space
contains all static variables.
The opposite of the Heap is the Stack. Each thread has its own stack
which contains:
* local variables and parameters
(Note: As mentioned before, if the variable is of a reference type,
there is only a memory pointer that points to the Heap)
Example:
class MyClass
{
public int MyValue;
}
class AnotherClass
{
public MyClass MyInstance;
}
class AThirdClass
{
int instanceVar;
public MyMethod(AnotherClass obj, int b)
{
// c is on stack so this isn't a problem.
int c = 10;
// d is a memory pointer on the stack.
// It is pointing to a MyClass object on the Heap.
// Since the object is newly created, no other threads can have
// access to it
MyClass d = new MyClass();
// Here is a potential problem. We are changing a MyInstance
// pointer on the Heap. This is a problem if another thread is
// accessing object obj at the same time.
obj.MyInstance = d;
// Also a problem. This also changes something on the heap.
obj.MyInstance.MyValue
// Another problem. instanceVar belongs to the current instance of
// AThirdClass so it is on the heap. If another thread is calling
// this method using the same object instance there could
// be a collision.
instanceVar = instanceVar+1;
}
}
--
Marcus Andrén