Re: Thread Communication Conceptual Question
Re: Thread Communication Conceptual Question
- Subject: Re: Thread Communication Conceptual Question
- From: Alastair Houghton <email@hidden>
- Date: Thu, 2 Aug 2007 11:34:52 +0100
On 2 Aug 2007, at 11:22, Filipe Varela wrote:
Chris, you're positively right as far as Cocoa apps go. There's no
need to get to the low-level uglyness i described.
Chris is right for other (non-Cocoa) apps too.
Now this is a Cocoa list so this could get off-topic real quick.
Yep.
Moving a bit closer to topic:
In this case, you could use a simple function with a pointer to the
data and a mutex to signal availability/change of data.
ie, main thread loop:
test mutex (non blocking test&set) {
// got here? we're unlocked
if data messed flag is set {
do stuff on data
unset flag
}
}
keep exec'ing loop
data producer/updated thread loop:
mess with work data
need to signal update? {
lock mutex
copy work data to shared data
set data messed flag to true
unlock mutex
}
I use this to track download progress in a plain ansi-c downloader
context.
The data messed flag is used to prevent the main thread to exec
stuff on data more often than necessary because it's possible to
get an unlocked mutex without having a data change...
There are two problems with this pattern:
1. You can't use it in a general purpose library, because you don't
have total control over the main thread.
2. It's very inefficient. You should be using a condition variable,
rather than polling a variable protected by a mutex. In Cocoa terms,
since this is a Cocoa list, you should be using NSConditionLock
rather than NSLock and your own variable.
e.g.
// Main loop
while (true) {
[myConditionLock lockWhenCondition:1];
// Data has changed
...
[myConditionLock unlockWithCondition:0];
}
// Other thread
while (working) {
// Do work
if (need to tell main thread) {
[myConditionLock lock];
// Set the data up for the main thread
[myConditionLock unlockWithCondition:1];
}
}
You *might* need to change the -lock to a -lockWhenCondition:0,
depending on whether it's OK for your main thread to miss an update
or not.
Of course, you'd never write the above in a full-blown Cocoa
application, right? Because if you did, you'd block event processing
and your app would beachball. Using a run loop source, or -
performSelectorOnMainThread:withObject:waitUntilDone: is a better bet
(though the above will work fine for a Foundation tool, for instance).
Kind regards,
Alastair.
--
http://alastairs-place.net
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden