void DecRef() { if (atomic_sub_uint32(&m_ref, 1) == 0) { delete this; } }
bool Lock(LockMode mode) { switch (mode) { case READ_LOCK: { for (;;) { // Wait for active writer to release the lock while (m_lock & 0xfff00000) sched_yield(); if ((0xfff00000 & atomic_add_uint32(&m_lock, 1)) == 0) return true; atomic_sub_uint32(&m_lock, 1); } return true; } case WRITE_LOCK: { // Wait for active writer to release the lock while (m_lock & 0xfff00000) sched_yield(); if ((0xfff00000 & atomic_add_uint32(&m_lock, 0x100000)) == 0x100000) { // Wait until there's no more readers while (m_lock & 0x000fffff) sched_yield(); return true; } atomic_sub_uint32(&m_lock, 0x100000); return true; } default: { return false; } } }
bool Unlock(LockMode mode) { switch (mode) { case READ_LOCK: { atomic_sub_uint32(&m_lock, 1); return true; } case WRITE_LOCK: { atomic_sub_uint32(&m_lock, 0x100000); return true; } default: { return false; } } }
int main(int argc, char const *argv[]) { uint64_t i64 = 10, c64; uint32_t i32 = 10, c32; c64 = atomic_add_uint64(&i64, 20); printf("%ld,%ld\n", i64, c64); i64 = 20; c64 = atomic_sub_uint64(&i64, 5); printf("%ld,%ld\n", i64, c64); c32 = atomic_add_uint32(&i32, 20); printf("%d,%d\n", i32, c32); i32 = 20; c32 = atomic_sub_uint32(&i32, 5); printf("%d,%d\n", i32, c32); return 0; }