I am afraid I am not completely sure what you mean by your first problem, but
hopefully my answer to your second one sidesteps your concern there. In answer
to your second (once I had parsed out the two different uses of the word
"block" in what you said!)...
> The second problem is that the pattern isn't actually thread safe. If two
> threads (that aren't the automatic thread of the queue) enter the accessor,
> two blocks will be enqueued serially. The two threads will then block,
> waiting for their blocks to finish executing.
>
> So far so good but when the first block finishes, it could happen that the
> first thread blocks until the second block finishes, at which time the foo
> value computed by the first block will have been replaced by the value
> computed by the second block, since foo is shared among all blocks that
> captured it.
If I understand you correctly, what you're saying about your variable "__block
SomeObjType foo" is not true. Regardless of the __block qualifier, foo is
effectively a stack-based variable, so two simultaneously-executing threads
have their own independent instance of that variable. There can be no
"cross-talk" between the variables in separate threads - all you are doing is
enabling the block that a given thread executes to have access to that specific
thread's stack variable.
However I don't think you should need to do this anyway. I would change your
code to something like this:
- (SomeObjType) foo
{
dispatch_sync(queue,
^{
// Code in this block ensures bah is valid
if (nil == bah)
{
// Code to compute and store bah goes here
}
});
return bah;
}
I'm pretty sure that will behave as you want. This does of course assume that
bah is created once and once only, and will never be released and set to nil
while threads are using it. That is a big assumption, but I'm pretty sure that
if you violate that condition then you are going to have to think VERY
carefully about how to actually specify "sensible" behaviour at all based on
this sort of accessor pattern, and do a lot of additional 'retain'ing of
objects.
What do you reckon?
Jonny_______________________________________________
Cocoa-dev mailing list ([email protected])
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 [email protected]