Re: Thread Question
Re: Thread Question
- Subject: Re: Thread Question
- From: Nathan Day <email@hidden>
- Date: Wed, 28 Apr 2004 16:56:26 +1000
On Wednesday, April 28, 2004, at 11:43AM, Dave Keck <email@hidden> wrote:
>
Say I have a thread, myThread, and I also have the main thread,
>
mainThread. I also have a method, myMethod:
>
>
Question 1: Is it OK to call myMethod from myThread? Is myMethod within
>
the "scope" of myMethod (assuming all this code is in the same class)?
Yes, that is what makes threads different from processors, thread exist within the same memory space.
>
Question 2: If Question #1 is "yes": is it safe to call myMethod from
>
both mainThread and myThread, possibly at the same time (if, say,
>
mainThread and myThread both had loops that called myMethod)? (Would I
>
have to use NSLocks for methods too?)
>
Question 3: If it is OK to call myMethod from both mainThread and
>
myThread: what happens when I do? Does it call the method by the same
>
address if I were to call it from mainThread and myThread, or does each
>
thread have its own "copy" of each method that it calls?
Each thread has it own local varibles, since they each have there own stack. If all myMethods does is use local varible and does not call any other functions or methods that aren't thread safe then you don't have to do anything, it is also safe to call myMethod from different threads if it accesses instance varibles but each thread is refering to a different instance of the class that implements myMethod. Otherwise you will probalbe have to use NSLock. You just have to look at your code and think about what would go wrong if two threads started manipulating the same varible at the same time, for something like a BOOL flag value which you just set then you probable don't need a lock. As an alternative to locks there are some atomic functions which can be used for basic stuff like increamenting a varible, I am sure I have listed these on this mailing list or the Omni one at least once before, these are good when you have to try and make the creation of your NSLock thread safe.
Nathan Day
email@hidden
http://homepage.mac.com/nathan_day/
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.