Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I want to run a block of code only once per instance.

Can I declare dispatch_once_t predicate as a member variable instead of static variable?

From GCD Reference, it is not clear to me.

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.

I know I can use dispatch_semaphore_t and a boolean flag to do the same thing. I'm just curious.

share|improve this question
    
just curious: could you cite me a sample in code how that can be achieved using dispatch_semaphore_t and a BOOL flag to do the same Thing? Thanks in advance. – Unheilig Jan 26 '14 at 6:04

dispatch_once_t must not be an instance variable.

The implementation of dispatch_once() requires that the dispatch_once_t is zero, and has never been non-zero. The previously-not-zero case would need additional memory barriers to work correctly, but dispatch_once() omits those barriers for performance reasons.

Instance variables are initialized to zero, but their memory may have previously stored another value. This makes them unsafe for dispatch_once() use.

share|improve this answer
2  
Could one work around these limitations by adding an OSMemoryBarrier() at the end of the object's init method? – Alej Apr 12 '14 at 18:22
    
Only pointer instance variables (and probably only object pointer instance variables), and even then only under ARC, are guaranteed to be initialized to zero. dispatch_once_t is a synonym for long, and hence is not guaranteed to be initialized to zero. – David Berry May 5 '14 at 18:23
7  
Not true. All Objective-C instance variables are guaranteed to be zero (except for ivars of C++ types which may be initialized using their zero-arg in-place constructor). – Greg Parker May 6 '14 at 14:17
3  
ARC adds zero initialization of local variables of ARC-managed object pointer types. – Greg Parker May 6 '14 at 14:18
3  
In any case, none of the above initializations are sufficient for dispatch_once use, because what is now the variable's storage may have been non-zero earlier in the process's life. – Greg Parker May 6 '14 at 14:19

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.

share|improve this answer
    
Thank you for the tests. I vote up your answer. It seems that I have to ask in Apple Forums for sure answer. – teerapap Dec 14 '12 at 7:40
1  
@teerapap - the comment on the definition of dispatch_once_t is: /* @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. */; which pretty much answers the question. I maybe should have looked up that comment earlier, but figuring out was fun... – CRD Dec 14 '12 at 19:19
3  
Some might think it's more interesting to look at the implementation of dispatch_once: trunk/src/once.c – rob mayoff Dec 14 '12 at 19:36
4  
This is incorrect. The requirement is not that the dispatch_once_t is initially zero, but that the dispatch_once_t has never been non-zero. Breaking that assumption may work most of the time, but if you are unlucky then the block may execute more than once or not at all. – Greg Parker Nov 7 '13 at 19:47
1  
@GregParker - Interesting. So the statement in the header ("It must be initialized to zero.") is inaccurate/imprecise? Given that the memory location will have been non-zero at some point in its history (its not brand new RAM), when does time start? I could venture an answer, but you will know :-) Just curious. – CRD Nov 8 '13 at 1:27

The reference you quote seems pretty clear: the predicate has to be in global or static scope, if you use it as a member variable, it will be dynamic, so the result will be undefined. So no, you can't. dispatch_once() is not what you're looking for (the reference also says: Executes a block object once and only once for the lifetime of an application, which is not what you want since you want this block to execute for each instance).

share|improve this answer
2  
I didn't notice the phase 'for the lifetime of an application'. However, it is possible to mean per instance for the lifetime of an application. – teerapap Dec 14 '12 at 7:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.