SpinLockTests.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include <stdio.h>
  2. #include <threads.h>
  3. #include "../Tests.h"
  4. #include "core/SpinLock.h"
  5. #include "core/Utility.h"
  6. typedef struct {
  7. mtx_t m;
  8. int counter;
  9. } MutexCounter;
  10. static int incrementMutexCounter(void* p) {
  11. MutexCounter* mcp = (MutexCounter*)p;
  12. for(int i = 0; i < 20000; i++) {
  13. mtx_lock(&mcp->m);
  14. mcp->counter++;
  15. mtx_unlock(&mcp->m);
  16. }
  17. return 0;
  18. }
  19. static void testMutex() {
  20. i64 n = -getNanos();
  21. MutexCounter mc = {.counter = 0};
  22. mtx_init(&mc.m, mtx_plain);
  23. thrd_t t[2];
  24. thrd_create(t + 0, incrementMutexCounter, &mc);
  25. thrd_create(t + 1, incrementMutexCounter, &mc);
  26. thrd_join(t[0], nullptr);
  27. thrd_join(t[1], nullptr);
  28. TEST_INT(40000, mc.counter);
  29. n += getNanos();
  30. printf("%ldns Mutex\n", n);
  31. }
  32. typedef struct {
  33. SpinLock s;
  34. int counter;
  35. } SpinLockCounter;
  36. static int incrementSpinLockCounter(void* p) {
  37. SpinLockCounter* mcp = (SpinLockCounter*)p;
  38. for(int i = 0; i < 20000; i++) {
  39. lockSpinLock(&mcp->s);
  40. mcp->counter++;
  41. unlockSpinLock(&mcp->s);
  42. }
  43. return 0;
  44. }
  45. static void testSpinLockLoop() {
  46. i64 n = -getNanos();
  47. SpinLockCounter sc = {.counter = 0};
  48. initSpinLock(&sc.s);
  49. thrd_t t[2];
  50. thrd_create(t + 0, incrementSpinLockCounter, &sc);
  51. thrd_create(t + 1, incrementSpinLockCounter, &sc);
  52. thrd_join(t[0], nullptr);
  53. thrd_join(t[1], nullptr);
  54. TEST_INT(40000, sc.counter);
  55. n += getNanos();
  56. printf("%ldns SpinLock\n", n);
  57. }
  58. void testSpinLock() {
  59. testMutex();
  60. testSpinLockLoop();
  61. }