counter.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "test/jemalloc_test.h"
  2. static const uint64_t interval = 1 << 20;
  3. TEST_BEGIN(test_counter_accum) {
  4. uint64_t increment = interval >> 4;
  5. unsigned n = interval / increment;
  6. uint64_t accum = 0;
  7. counter_accum_t c;
  8. counter_accum_init(&c, interval);
  9. tsd_t *tsd = tsd_fetch();
  10. bool trigger;
  11. for (unsigned i = 0; i < n; i++) {
  12. trigger = counter_accum(tsd_tsdn(tsd), &c, increment);
  13. accum += increment;
  14. if (accum < interval) {
  15. expect_b_eq(trigger, false, "Should not trigger");
  16. } else {
  17. expect_b_eq(trigger, true, "Should have triggered");
  18. }
  19. }
  20. expect_b_eq(trigger, true, "Should have triggered");
  21. }
  22. TEST_END
  23. void
  24. expect_counter_value(counter_accum_t *c, uint64_t v) {
  25. uint64_t accum = locked_read_u64_unsynchronized(&c->accumbytes);
  26. expect_u64_eq(accum, v, "Counter value mismatch");
  27. }
  28. #define N_THDS (16)
  29. #define N_ITER_THD (1 << 12)
  30. #define ITER_INCREMENT (interval >> 4)
  31. static void *
  32. thd_start(void *varg) {
  33. counter_accum_t *c = (counter_accum_t *)varg;
  34. tsd_t *tsd = tsd_fetch();
  35. bool trigger;
  36. uintptr_t n_triggered = 0;
  37. for (unsigned i = 0; i < N_ITER_THD; i++) {
  38. trigger = counter_accum(tsd_tsdn(tsd), c, ITER_INCREMENT);
  39. n_triggered += trigger ? 1 : 0;
  40. }
  41. return (void *)n_triggered;
  42. }
  43. TEST_BEGIN(test_counter_mt) {
  44. counter_accum_t shared_c;
  45. counter_accum_init(&shared_c, interval);
  46. thd_t thds[N_THDS];
  47. unsigned i;
  48. for (i = 0; i < N_THDS; i++) {
  49. thd_create(&thds[i], thd_start, (void *)&shared_c);
  50. }
  51. uint64_t sum = 0;
  52. for (i = 0; i < N_THDS; i++) {
  53. void *ret;
  54. thd_join(thds[i], &ret);
  55. sum += (uintptr_t)ret;
  56. }
  57. expect_u64_eq(sum, N_THDS * N_ITER_THD / (interval / ITER_INCREMENT),
  58. "Incorrect number of triggers");
  59. }
  60. TEST_END
  61. int
  62. main(void) {
  63. return test(
  64. test_counter_accum,
  65. test_counter_mt);
  66. }