Skip to content

Instantly share code, notes, and snippets.

@lilyball
Created August 6, 2010 00:20
Show Gist options
  • Save lilyball/510624 to your computer and use it in GitHub Desktop.
Save lilyball/510624 to your computer and use it in GitHub Desktop.
typedef long my_dispatch_once_t;
typedef void (^my_dispatch_block_t)(void);
void my_dispatch_once(my_dispatch_once_t *predicate, my_dispatch_block_t block);
#include "MyDispatchOnce.h"
#import <libkern/OSAtomic.h>
#if defined(__i386__) || defined(__x86_64__)
#define my_hardware_pause() __asm__("pause")
#else
#define my_hardware_pause() __asm__("")
#endif
// this is a shameless copy of dispatch_once()
void my_dispatch_once(my_dispatch_once_t *predicate, my_dispatch_block_t block) {
volatile long *val = predicate;
if (OSAtomicCompareAndSwapLong(0l, 1l, val)) {
block();
OSMemoryBarrier();
*val = ~0l;
} else {
do {
// hardware pause
my_hardware_pause();
} while (*val != ~0l);
OSMemoryBarrier();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment