mq.c 1.8 KB

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