Last active
January 31, 2017 13:31
-
-
Save dimazen/94c4bfaaf2e36e24c49cbe54e266ddb0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Atomic<T> { | |
private var _value: T | |
var value: T { | |
mutating get { | |
var result: T | |
_atomic_lock_object(&self) | |
result = _value | |
_atomic_unlock_object(&self) | |
return result | |
} | |
set { | |
_atomic_lock_object(&self) | |
_value = newValue | |
_atomic_unlock_object(&self) | |
} | |
} | |
init(_ value: T) { | |
_value = value | |
} | |
} | |
// AtomicLock.h (goes to the bridging header) | |
#ifndef AtomicLock_h | |
#define AtomicLock_h | |
void _atomic_lock_object(void * _Nonnull object); | |
void _atomic_unlock_object(void * _Nonnull object); | |
#endif /* AtomicLock_h */ | |
// AtomicLock.c | |
#include "AtomicLock.h" | |
#include <os/lock.h> | |
const int32_t GOODPOWER = 7; | |
const int32_t GOODMASK = (1 << GOODPOWER) - 1; | |
OS_ALWAYS_INLINE int32_t goodhash(int32_t value) { | |
return (value >> 5) & GOODMASK; | |
} | |
static os_unfair_lock PropertyLocks[1 << GOODPOWER] = { 0 }; | |
void _atomic_lock_object(void *object) { | |
int32_t slot = goodhash((int32_t)object); | |
os_unfair_lock_lock(&PropertyLocks[slot]); | |
} | |
void _atomic_unlock_object(void *object) { | |
int32_t slot = goodhash((int32_t)object); | |
os_unfair_lock_unlock(&PropertyLocks[slot]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment