2
0

mtx.c 1008 B

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