On Thu, Feb 12, 2009 at 4:25 AM, Oleg Krupnov <oleg.krup...@gmail.com> wrote:
> This seems a trivial question for a multi-threading app, but I haven't
> been successful in implementing this in Cocoa. I've got deadlocks and
> strange logs for seemingly no reason.
>
> Here's my problem: There is the main thread that starts a worker
> NSOperation to do some job (-[NSOperationQueue addOperation]). In case
> if the main thread is asked to start another NSOperation, it must
> cancel the current operation, *wait until it exits*, and start another
> one.
>
> What I have tried: the operation object creates and locks an NSLock
> object in its -init. When the main thread cancels the operation
> (-cancel), it does the following:
>
> // cancel
> [m_operation cancel];
> // wait until operation exits
> [[m_operation isCompletedLock] lock];
>
> // the operation object eventually checks the -isCancelled flag and
> then sends -unlock to the lock, and its thread exits.
>
> // unlock the lock
> [[m_operation isCompletedLock] unlock];
> // release
> [m_operation release];
> m_operation = nil;

Yeah, don't do this. Locks are for mutual exclusion *only*.

Use NSConditionLock, something like this:

#define OPERATION_FINISHED 1

// operation exit
[condLock lock];
[condLock unlockWithCondition:OPERATION_FINISHED];

// wait for exit
[condLock lockWhenCondition:OPERATION_FINISHED];
[condLock unlock];

Mike
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to