#include #include #include #include "../Tests.h" #include "core/SpinLock.h" #include "core/Utility.h" typedef struct { mtx_t m; int counter; } MutexCounter; static int incrementMutexCounter(void* p) { MutexCounter* mcp = (MutexCounter*)p; for(int i = 0; i < 20000; i++) { mtx_lock(&mcp->m); mcp->counter++; mtx_unlock(&mcp->m); } return 0; } static void testMutex() { i64 n = -getNanos(); MutexCounter mc = {.counter = 0}; mtx_init(&mc.m, mtx_plain); thrd_t t[2]; thrd_create(t + 0, incrementMutexCounter, &mc); thrd_create(t + 1, incrementMutexCounter, &mc); thrd_join(t[0], nullptr); thrd_join(t[1], nullptr); TEST_INT(40000, mc.counter); n += getNanos(); printf("%" PRId64 "ns Mutex\n", n); } typedef struct { SpinLock s; int counter; } SpinLockCounter; static int incrementSpinLockCounter(void* p) { SpinLockCounter* mcp = (SpinLockCounter*)p; for(int i = 0; i < 20000; i++) { lockSpinLock(&mcp->s); mcp->counter++; unlockSpinLock(&mcp->s); } return 0; } static void testSpinLockLoop() { i64 n = -getNanos(); SpinLockCounter sc = {.counter = 0}; initSpinLock(&sc.s); thrd_t t[2]; thrd_create(t + 0, incrementSpinLockCounter, &sc); thrd_create(t + 1, incrementSpinLockCounter, &sc); thrd_join(t[0], nullptr); thrd_join(t[1], nullptr); TEST_INT(40000, sc.counter); n += getNanos(); printf("%" PRId64 "ns SpinLock\n", n); } void testSpinLock() { testMutex(); testSpinLockLoop(); }