Re: Specific Multithreading Issues
Re: Specific Multithreading Issues
- Subject: Re: Specific Multithreading Issues
- From: "Dennis C. De Mars" <email@hidden>
- Date: Fri, 04 May 2001 10:56:43 -0700
on 5/4/01 9:43 AM, Miguel Morales at email@hidden wrote:
>
Hello all, I just joined the list, so I hope this is not a repetitive
>
question. First, is there any good documentation on multithreading with
>
foundation? If so where can I find it?
>
>
Now on to the specific multithreading question.
>
>
I'm developing a very high performance scientific analysis program (I'm
>
sifting through mountains of real time data looking for Gamma Ray
>
Bursts), and I'm planning to use distributed objects and threads to get
>
the most out of small cluster of multiple CPU machines. In my analysis
>
I will divide the problem up into several identical pieces (each a
>
separate class instance), each running in it's own thread. Since I have
>
separate instances all of the instance variables should be fine with
>
multithreading. What I'm worrying about is temporary variables. Say in
>
my class I have a method of the following form:
>
>
-myMethod
>
{
>
int i;
>
>
for(i = 0; i<1000; i++)
>
{
>
do something with instance variables ...
>
}
>
}
>
>
How does the compiler handle the variable i? This method will get
>
called at the same time by multiple threads, but only in the context of
>
separate instances. If the variable i is associated with the instance
>
of the class (even though it is not an instance variable per se), I'm
>
home free. However, if the variable i is associated with the
>
instruction code then I'll have multithreading issues.
What, there is no gamma ray burst counter object in the Interface Builder?
But seriously, folks...
In your example, "i" is indeed associated with the code, not the object, but
there are no multithreading issues here. "i" is allocated on the stack, or
possibly optimized by the compiler to be assigned to a CPU register, but
either way, it's OK because each thread has its own set of registers and its
own stack (really the part of the stack used after the point the thread was
created). Together these are called the thread's context, and the context is
switched whenever execution is switched from one thread to another.
The fact that a variable is allocated on the stack also makes it safe for a
function to call itself recursively. Basically, each invocation of the
function creates a new set of local variables.
Now, what would be bad is if you declared i to be "static." Then all
invocations of the function would share a single instance of i and then you
couldn't reliably call the function from multiple threads.
(In the above I used the term "function" instead of "method" but all of the
above applies to methods also).
Note on terminology: variables like "i" are usually referred to as
"automatic" variables.
- Dennis D.