|
7 | 7 |
|
8 | 8 | #import "MAKVONotificationCenter.h"
|
9 | 9 |
|
10 |
| -#import <libkern/OSAtomic.h> |
| 10 | +#import <stdatomic.h> |
11 | 11 | #import <objc/message.h>
|
12 | 12 |
|
13 | 13 | #if (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060)
|
@@ -119,37 +119,12 @@ @implementation MAKVONotificationCenter
|
119 | 119 |
|
120 | 120 | + (id)defaultCenter
|
121 | 121 | {
|
122 |
| - static MAKVONotificationCenter *center = nil; |
123 |
| - if(!center) |
124 |
| - { |
125 |
| - // Do a bit of clever atomic setting to make this thread safe. |
126 |
| - // If two threads try to set simultaneously, one will fail |
127 |
| - // and the other will set things up so that the failing thread |
128 |
| - // gets the shared center... |
129 |
| - |
130 |
| - MAKVONotificationCenter *newCenter = [[self alloc] init]; |
131 |
| - // objc_atomicCompareAndSwapGlobalBarrier() is not documented. We |
132 |
| - // assume it behaves as OSAtomicCompareAndSwapPtrBarrier(), with the |
133 |
| - // same signature. The first argument, 'predicate', is interpreted |
134 |
| - // to the the "pre-existing" value or '__oldValue' of |
135 |
| - // OSAtomicCompareAndSwapPtrBarrier(). |
136 |
| - // In our usage, either method supposedly compares center to nil, |
137 |
| - // if center is nil, sets center to newCenter and returns true |
138 |
| - // Note that this whole code block is if(!center). |
139 |
| - // This is thus the normal behavior when no thread race occurs |
140 |
| - // if center is not nil, does nothing and returns false |
141 |
| - // This will happen if another thread snuck in and set it. |
142 |
| - |
143 |
| - // Mike's original code, does not support Garbage Collection but works |
144 |
| - // in 10.5 and earlier |
145 |
| - BOOL weWon = OSAtomicCompareAndSwapPtrBarrier(nil, newCenter, (void *)¢er) ; |
146 |
| - if (!weWon) { |
147 |
| - // Thread race has occurred and we lost |
148 |
| - // center has previously been set to newCenter by another thread |
149 |
| - [newCenter release]; |
150 |
| - } |
151 |
| - } |
152 |
| - return center; |
| 122 | + static MAKVONotificationCenter* center = nil; |
| 123 | + static dispatch_once_t onceToken = 0; |
| 124 | + dispatch_once(&onceToken, ^ { |
| 125 | + center = [[MAKVONotificationCenter alloc] init]; |
| 126 | + }); |
| 127 | + return center; |
153 | 128 | }
|
154 | 129 |
|
155 | 130 | - (id)init
|
|
0 commit comments