Re: Lockless thread-safe accessor using blocks: how to?
Re: Lockless thread-safe accessor using blocks: how to?
- Subject: Re: Lockless thread-safe accessor using blocks: how to?
- From: Jonathan Taylor <email@hidden>
- Date: Thu, 14 Apr 2011 17:19:43 +0100
Hi WT,
>> 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.
>
> I'm afraid you're incorrect there. According to the documentation (or, more precisely, my understanding of the documentation), a variable qualified with __block starts in the stack but is moved to the heap, precisely because it's shared by all blocks capturing it and by all function scopes where it's declared. Therefore, I do not believe "two simultaneously-executing threads have their own independent instance of that variable" to be true.
I tested this out before replying as I wasn't 100% certain. It may be that we have misunderstood each other somehow, but the following code (in a clean new project) was what I used to confirm to myself that two concurrently-executing threads have independent instances of the variable:
http://www.dur.ac.uk/j.m.taylor/block_test_code.m
>> 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 don't see how that could possibly work as is because bah is out of scope by the time the return statement is executed. Perhaps you meant that bah is an ivar or property declared in the same class as the accessor. I'm suddenly drawing a blank here because I considered this before and came to the conclusion that it wouldn't work but now I can't remember why I thought that way. I need to think this through a bit more.
OK, well since you do not declare bah locally, and from what you are doing it is presumably meant to be persistent, I assumed that it was indeed a property (or a global?). If you are doing something else with it (though I'm not quite sure what...) then obviously what I wrote may be wrong...
Jonny_______________________________________________
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