SpinLockTests.c 1.6 KB

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