mtx.c 1003 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "test/jemalloc_test.h"
  2. #define NTHREADS 2
  3. #define NINCRS 2000000
  4. TEST_BEGIN(test_mtx_basic)
  5. {
  6. mtx_t mtx;
  7. assert_false(mtx_init(&mtx), "Unexpected mtx_init() failure");
  8. mtx_lock(&mtx);
  9. mtx_unlock(&mtx);
  10. mtx_fini(&mtx);
  11. }
  12. TEST_END
  13. typedef struct {
  14. mtx_t mtx;
  15. unsigned x;
  16. } thd_start_arg_t;
  17. static void *
  18. thd_start(void *varg)
  19. {
  20. thd_start_arg_t *arg = (thd_start_arg_t *)varg;
  21. unsigned i;
  22. for (i = 0; i < NINCRS; i++) {
  23. mtx_lock(&arg->mtx);
  24. arg->x++;
  25. mtx_unlock(&arg->mtx);
  26. }
  27. return (NULL);
  28. }
  29. TEST_BEGIN(test_mtx_race)
  30. {
  31. thd_start_arg_t arg;
  32. thd_t thds[NTHREADS];
  33. unsigned i;
  34. assert_false(mtx_init(&arg.mtx), "Unexpected mtx_init() failure");
  35. arg.x = 0;
  36. for (i = 0; i < NTHREADS; i++)
  37. thd_create(&thds[i], thd_start, (void *)&arg);
  38. for (i = 0; i < NTHREADS; i++)
  39. thd_join(thds[i], NULL);
  40. assert_u_eq(arg.x, NTHREADS * NINCRS,
  41. "Race-related counter corruption");
  42. }
  43. TEST_END
  44. int
  45. main(void)
  46. {
  47. return (test(
  48. test_mtx_basic,
  49. test_mtx_race));
  50. }