mq.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include "test/jemalloc_test.h"
  2. #define NSENDERS 3
  3. #define NMSGS 100000
  4. typedef struct mq_msg_s mq_msg_t;
  5. struct mq_msg_s {
  6. mq_msg(mq_msg_t) link;
  7. };
  8. mq_gen(static, mq_, mq_t, mq_msg_t, link)
  9. TEST_BEGIN(test_mq_basic) {
  10. mq_t mq;
  11. mq_msg_t msg;
  12. assert_false(mq_init(&mq), "Unexpected mq_init() failure");
  13. assert_u_eq(mq_count(&mq), 0, "mq should be empty");
  14. assert_ptr_null(mq_tryget(&mq),
  15. "mq_tryget() should fail when the queue is empty");
  16. mq_put(&mq, &msg);
  17. assert_u_eq(mq_count(&mq), 1, "mq should contain one message");
  18. assert_ptr_eq(mq_tryget(&mq), &msg, "mq_tryget() should return msg");
  19. mq_put(&mq, &msg);
  20. assert_ptr_eq(mq_get(&mq), &msg, "mq_get() should return msg");
  21. mq_fini(&mq);
  22. }
  23. TEST_END
  24. static void *
  25. thd_receiver_start(void *arg) {
  26. mq_t *mq = (mq_t *)arg;
  27. unsigned i;
  28. for (i = 0; i < (NSENDERS * NMSGS); i++) {
  29. mq_msg_t *msg = mq_get(mq);
  30. assert_ptr_not_null(msg, "mq_get() should never return NULL");
  31. dallocx(msg, 0);
  32. }
  33. return NULL;
  34. }
  35. static void *
  36. thd_sender_start(void *arg) {
  37. mq_t *mq = (mq_t *)arg;
  38. unsigned i;
  39. for (i = 0; i < NMSGS; i++) {
  40. mq_msg_t *msg;
  41. void *p;
  42. p = mallocx(sizeof(mq_msg_t), 0);
  43. assert_ptr_not_null(p, "Unexpected mallocx() failure");
  44. msg = (mq_msg_t *)p;
  45. mq_put(mq, msg);
  46. }
  47. return NULL;
  48. }
  49. TEST_BEGIN(test_mq_threaded) {
  50. mq_t mq;
  51. thd_t receiver;
  52. thd_t senders[NSENDERS];
  53. unsigned i;
  54. assert_false(mq_init(&mq), "Unexpected mq_init() failure");
  55. thd_create(&receiver, thd_receiver_start, (void *)&mq);
  56. for (i = 0; i < NSENDERS; i++) {
  57. thd_create(&senders[i], thd_sender_start, (void *)&mq);
  58. }
  59. thd_join(receiver, NULL);
  60. for (i = 0; i < NSENDERS; i++) {
  61. thd_join(senders[i], NULL);
  62. }
  63. mq_fini(&mq);
  64. }
  65. TEST_END
  66. int
  67. main(void) {
  68. return test(
  69. test_mq_basic,
  70. test_mq_threaded);
  71. }