mq.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. expect_false(mq_init(&mq), "Unexpected mq_init() failure");
  13. expect_u_eq(mq_count(&mq), 0, "mq should be empty");
  14. expect_ptr_null(mq_tryget(&mq),
  15. "mq_tryget() should fail when the queue is empty");
  16. mq_put(&mq, &msg);
  17. expect_u_eq(mq_count(&mq), 1, "mq should contain one message");
  18. expect_ptr_eq(mq_tryget(&mq), &msg, "mq_tryget() should return msg");
  19. mq_put(&mq, &msg);
  20. expect_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. expect_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. expect_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. expect_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. }