spinlock.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* Poor man's spinlock test */
  2. #include "spinlock.h"
  3. #include <pthread.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #define TEST_TIMES 1000
  7. static spinlock_t guard = INIT_SPINLOCK_UNLOCKED;
  8. static spinlock_t go = INIT_SPINLOCK_UNLOCKED;
  9. static volatile int x = 0;
  10. static int set_expect(int s, int e) {
  11. int ret = 0;
  12. spinlock_lock(&guard);
  13. spinlock_unlock(&go);
  14. if (x != e) {
  15. ret = 1;
  16. goto out;
  17. }
  18. x = s;
  19. out:
  20. spinlock_unlock(&guard);
  21. return ret;
  22. }
  23. static void* thr(void* unused) {
  24. spinlock_lock(&go);
  25. if (set_expect(0, -1)) {
  26. return (void*)1;
  27. }
  28. return (void*)0;
  29. }
  30. static void do_test(void) {
  31. pthread_t th;
  32. int ret_val = 0;
  33. spinlock_lock(&go);
  34. pthread_create(&th, NULL, thr, NULL);
  35. if (set_expect(-1, 0)) {
  36. puts("Test failed!");
  37. exit(1);
  38. }
  39. pthread_join(th, (void**)&ret_val);
  40. if (ret_val) {
  41. puts("Test failed!");
  42. exit(1);
  43. }
  44. }
  45. int main(void) {
  46. setbuf(stdout, NULL);
  47. for (int i = 0; i < TEST_TIMES; ++i) {
  48. do_test();
  49. }
  50. puts("Test successful!");
  51. return 0;
  52. }