Re: question: NSThread & NSLock
Re: question: NSThread & NSLock
- Subject: Re: question: NSThread & NSLock
- From: James Bucanek <email@hidden>
- Date: Mon, 29 May 2006 07:22:33 -0700
Karim Morsy wrote on Monday, May 29, 2006:
>Hi Chris,
>
>> It's not clear to me what's going on here. You've got a worker
>> thread and a GUI thread, what's the third thread?
>
>no, every time the user selects an audio file one thread is detached
>that performs the initialization. that thread finishes execution as
>soon as he leaves the critical section and notifies the main thread.
>this works fine.
>in case the user decides to load a different file while the thread
>hasn't finished loading, a new thread is detached and tries to
>acquire the lock. the thread that has been running stops its regular
>control flow, cleans up , releases the lock and the
>thread that has been waiting enters and loads the newly selected file.
>this case also works fine.
>things start getting problematic when one thread is loading, and the
>user clicks twice on a different audio file (within a short period of
>time).
>while the first thread is still cleaning up and hasn't unlocked, 2
>threads have been detached and try to enter. I only want the user's
>last selection to take effect.
>(the gui is not affected by the locking).
>I haven't been able to come up with an ideal solution for this.
If you want to control the order of things, then you need to devise a data structure that will keep your requests in order.
There are probably a thousand different ways of solving this problem. It sounds like you are are spawning a thread on every user request and simply want the last thread to run and all other previously started threads to abort. It also sounds like your threads are polling to determine if they should stop.
So here's one solution: Keep an NSArray of which worker threads you've started. When the thread starts it's added to the end of the array. When a thread finishes, it is removed. All access to the shared array would be protected with a single NSLock. You could modify the threads to poll to see if they are still the most recently added thread and shut down if they are not ([workerLock lock]; BOOL shouldStop = (self!=[workerList lastObject]); [workerLock unlock]; ...). The act of adding a thread to the array would automatically signal all other threads in the array that they should terminate.
This is a bit lame, and there are certainly many other ways of accomplishing this with various degrees of complexity, elegance, and encapsulation. But it sounds like your GUI and worker threads are already deeply entangled, so this solution shouldn't distress your program design too much.
--
James Bucanek
_______________________________________________
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