Re: NSLock locking order;
Re: NSLock locking order;
- Subject: Re: NSLock locking order;
- From: Alastair Houghton <email@hidden>
- Date: Mon, 14 Nov 2005 16:19:39 +0000
On 10 Nov 2005, at 23:30, Matt Budd (Madentec) wrote:
Hey Joseph,
I can't do the first suggestion, because that implies that the
worker thread is being turned on sporadically to do some work. It
is the opposite case, the worker thread is constantly evaluating
these numbers and accumulations, and only sporadically the main
thread is going to interrupt him and tell him to either accumulate
in a different direction or to start also accumulating additional
numbers. The the worker thread is going all the time, I just want
to stop it when I know there is an state update going to happen.
Hi Matt,
If the worker thread is going all the time anyway, then just use a
volatile boolean variable and test it at convenient points in the
worker thread's loop. Then when your main thread wants to make a
change and needs to stop the worker thread, have it set the variable
and try to lock a condition lock. The worker thread can then unlock
the same condition lock and then try to lock it again... e.g.
/* -- Declarations (probably within an object instance) -- */
NSConditionLock *condLock;
volatile BOOL needsToStop;
/* Initially, condLock should be locked by the worker thread, with
condition 0;
the needsToStop variable should be set to NO. */
/* -- Worker thread -- */
while (1) {
if (needsToStop) {
/* Let main thread do whatever */
[condLock unlockWithCondition:1];
/* Wait for main thread to finish doing its stuff */
[condLock lockWhenCondition:0];
/* Perhaps reset variables or something here */
}
/* Other work... */
}
/* -- Main thread -- */
/* Tell worker thread to wait */
needsToStop = YES;
[condLock lockWhenCondition:1];
/* Do whatever... */
/* Allow worker thread to restart */
needsToStop = NO;
[condLock unlockWithCondition:0];
The queue paradigm that was suggested by someone else is more useful
for the case where the worker thread is handed tasks to complete by
the main thread... you could use a queue here instead, but polling it
might be expensive if you have to lock it to check for a waiting
message.
Kind regards,
Alastair.
--
http://www.alastairs-place.net
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden