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