seq.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include "test/jemalloc_test.h"
  2. #include "jemalloc/internal/seq.h"
  3. typedef struct data_s data_t;
  4. struct data_s {
  5. int arr[10];
  6. };
  7. static void
  8. set_data(data_t *data, int num) {
  9. for (int i = 0; i < 10; i++) {
  10. data->arr[i] = num;
  11. }
  12. }
  13. static void
  14. expect_data(data_t *data) {
  15. int num = data->arr[0];
  16. for (int i = 0; i < 10; i++) {
  17. expect_d_eq(num, data->arr[i], "Data consistency error");
  18. }
  19. }
  20. seq_define(data_t, data)
  21. typedef struct thd_data_s thd_data_t;
  22. struct thd_data_s {
  23. seq_data_t data;
  24. };
  25. static void *
  26. seq_reader_thd(void *arg) {
  27. thd_data_t *thd_data = (thd_data_t *)arg;
  28. int iter = 0;
  29. data_t local_data;
  30. while (iter < 1000 * 1000 - 1) {
  31. bool success = seq_try_load_data(&local_data, &thd_data->data);
  32. if (success) {
  33. expect_data(&local_data);
  34. expect_d_le(iter, local_data.arr[0],
  35. "Seq read went back in time.");
  36. iter = local_data.arr[0];
  37. }
  38. }
  39. return NULL;
  40. }
  41. static void *
  42. seq_writer_thd(void *arg) {
  43. thd_data_t *thd_data = (thd_data_t *)arg;
  44. data_t local_data;
  45. memset(&local_data, 0, sizeof(local_data));
  46. for (int i = 0; i < 1000 * 1000; i++) {
  47. set_data(&local_data, i);
  48. seq_store_data(&thd_data->data, &local_data);
  49. }
  50. return NULL;
  51. }
  52. TEST_BEGIN(test_seq_threaded) {
  53. thd_data_t thd_data;
  54. memset(&thd_data, 0, sizeof(thd_data));
  55. thd_t reader;
  56. thd_t writer;
  57. thd_create(&reader, seq_reader_thd, &thd_data);
  58. thd_create(&writer, seq_writer_thd, &thd_data);
  59. thd_join(reader, NULL);
  60. thd_join(writer, NULL);
  61. }
  62. TEST_END
  63. TEST_BEGIN(test_seq_simple) {
  64. data_t data;
  65. seq_data_t seq;
  66. memset(&seq, 0, sizeof(seq));
  67. for (int i = 0; i < 1000 * 1000; i++) {
  68. set_data(&data, i);
  69. seq_store_data(&seq, &data);
  70. set_data(&data, 0);
  71. bool success = seq_try_load_data(&data, &seq);
  72. expect_b_eq(success, true, "Failed non-racing read");
  73. expect_data(&data);
  74. }
  75. }
  76. TEST_END
  77. int main(void) {
  78. return test_no_reentrancy(
  79. test_seq_simple,
  80. test_seq_threaded);
  81. }