Update Aug 16
This Q&A was brought to my attention again and I thought I should update it. The original answer will be left at the end for the history.
I am going to seemingly disagree with Greg Parker, but probably not really...
The original question:
Can I declare dispatch_once_t predicate as a member variable instead of static variable?
Short Answer: The answer is yes PROVIDED there is a memory barrier between the initial creation of the object and any use of dispatch_once.
Quick Explanation: The requirement on the dispatch_once_t variable for dispatch_once is that it must be initially zero. The difficult comes from memory re-ordering operations on modern multiprocessors. While it may appear that a store to a location has been performed according to the program text (high level language or assembler level) the actual store may be reordered and occur after a subsequent read of the same location. To address this memory barriers can be used which force all memory operations occurring before them to complete before those following them. Apple provides the OSMemoryBarrier() to do this.
With dispatch_once Apple is stating that zero-initialised global variables are guaranteed to be zero, but that the zero-initialised instance variables (and zero initialising is the Objective-C default here) are not guaranteed to be zero before a dispatch_once is executed.
The solution is to insert a memory barrier; on the assumption that the dispatch_once occurs in some member method of an instance the obvious place to put this memory barrier is in the init method as (1) it will only be executed once (per instance) and (2) init must have returned before any other member method can be called.
So yes, with an appropriate memory barrier, dispatch_once can be used with an instance variable.
Original Answer
Interesting question, let's muse a little...
A simple read of:
The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage is undefined.
would be that the answer is that you cannot use a member variable as it is dynamically allocated, but...
Consider: When passed an address of the dispatch_once_t how would dispatch_once know whether it pointed to an global/static or not? While this can be determined, or at least decently guessed at, what would knowing this allow dispatch_once to do?
It seems more likely that it is not whether the address refers to dynamic or statically allocated memory that is important, but the semantics of the storage contents (and not its address - and storage is just an address and some contents) that is implied by static vs. dynamic allocation.
Now GCD is a C API, and in C global/static storage is guaranteed to be zero if not otherwise initialised; while automatic/local & dynamic storage has random garbage initially. Further note that no initialisation of the dispatch_once_t structure is required by dispatch_once. So we could hypothesise that the requirement for global/static storage is in fact a requirement for initial-zero storage...
Alternatively we could consider the address of the dispatch_once_t structure as being of significance. Global/static variables have fixed addresses, while an auto/local variable might have a different address at each invocation. A dynamically allocated variable in C would usually also have a fixed address (as there is no garbage collector, so certainly no relocating garbage collector!), but maybe realloc() could change an address. So we could alternatively hypothesise that the requirement is for something with a fixed address, though this seems far less likely than the initial-zero possibility.
And if that hypothesis is correct we can note that instance variables in Objective-C are guaranteed to be initially zero, and that (dynamically allocated) objects also have fixed addresses (there is no realloc() equivalent) - satisfying both hypotheses. That in turn would suggest that an instance variable can be used.
Of course I don't know that they can... but is seems reasonable. Let's see what others think, sound reasonable or am I just suffering from too little sleep and my brain is addled? ;-)
Addendum
No comments yet pro/con this little amusement, but sleep has been had and some quick code has been scrawled:
@implementation One
{
int myCount;
}
static dispatch_once_t onceToken;
static int Counter = 0;
static One *SharedOne;
- (id) init
{
if((self = [super init]))
{
myCount = ++Counter;
NSLog(@"init: One#%d", myCount);
dispatch_once(&onceToken, ^{
SharedOne = self;
});
}
return self;
}
- (void) identify
{
NSLog(@"identify: One#%d", myCount);
}
+ (void) identifyShared
{
[SharedOne identify];
}
+ (void) clobber
{
bzero(&onceToken, sizeof(dispatch_once_t));
}
@end
Now One does things the standard way using a static, but for one wrinkle. To test the hypothesis the method clobber re-zeroes the onceToken to see what happens. Now a second class:
@implementation Two
{
dispatch_once_t onceToken;
int counter;
}
- (void) countCalls
{
dispatch_once(&onceToken, ^{
counter = 0;
});
NSLog(@"countCalls: %d", ++counter);
}
- (void) clobber
{
bzero(&onceToken, sizeof(dispatch_once_t));
}
@end
Now Two does things the non-standard way using an instance variable. The first, and only the first, call to countCalls should zero counter, and every call should increment it. Our friend clobber is there to test hypothesis again. So a quick app delegate to test this:
@implementation CLAppDelegate
@synthesize window = _window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
One *a1, *b1, *c1;
a1 = [One new];
b1 = [One new];
[One identifyShared];
[One clobber];
c1 = [One new];
[One identifyShared];
Two *a2;
a2 = [Two new];
[a2 countCalls];
[a2 countCalls];
[a2 clobber];
[a2 countCalls];
}
@end
And the output is:
init: One#1
init: One#2
identify: One#1
init: One#3
identify: One#3
countCalls: 1
countCalls: 2
countCalls: 1
init: One#1
init: One#2
identify: One#1
init: One#3
identify: One#3
countCalls: 1
countCalls: 2
countCalls: 1
So in these two cases the hypothesis holds - that the dispatch_once_t variable being initialised to zero and have a lifetime greater than any call to dispatch_once() that uses it is the essential part. By zeroing the variable the dispatch_once() was made to re-fire, and using an instance variable worked fine.
Disclaimer: This is just for fun, no warranty whatsoever etc. We made a hypothesis and two simple, non-exhaustive, tests which supported it. YMMV.
Hope that assuages your curiosity somewhat. Thanks for an interesting question!
And if someone can point out the obvious that I've missed please do!
Addendum 2
The definition of dispach_once_t from Apple's headers:
typedef long dispatch_once_t;
/*!
* @typedef dispatch_once_t
*
* @abstract
* A predicate for use with dispatch_once(). It must be initialized to zero.
* Note: static and global variables default to zero.
*/
typedef long dispatch_once_t;
Now we could have started by looking this up, but that wouldn't have been so interesting.