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