diff --git a/core/include/msg.h b/core/include/msg.h index 8e814987fb..01a22a0805 100644 --- a/core/include/msg.h +++ b/core/include/msg.h @@ -224,6 +224,14 @@ int msg_reply(msg_t *m, msg_t *reply); */ int msg_reply_int(msg_t *m, msg_t *reply); +/** + * @brief Check how many messages are available in the message queue + * + * @return Number of messages available in our queue on success + * @return -1, if no caller's message queue is initialized + */ +int msg_avail(void); + /** * @brief Initialize the current thread's message queue. * diff --git a/core/msg.c b/core/msg.c index d0f66e060f..8d2262063e 100644 --- a/core/msg.c +++ b/core/msg.c @@ -370,6 +370,22 @@ static int _msg_receive(msg_t *m, int block) DEBUG("This should have never been reached!\n"); } +int msg_avail(void) +{ + DEBUG("msg_available: %" PRIkernel_pid ": msg_available.\n", + sched_active_thread->pid); + + tcb_t *me = (tcb_t*) sched_active_thread; + + int queue_index = -1; + + if (me->msg_array) { + queue_index = cib_avail(&(me->msg_queue)); + } + + return queue_index; +} + int msg_init_queue(msg_t *array, int num) { /* check if num is a power of two by comparing to its complement */ diff --git a/tests/thread_msg_avail/Makefile b/tests/thread_msg_avail/Makefile new file mode 100644 index 0000000000..711d191b67 --- /dev/null +++ b/tests/thread_msg_avail/Makefile @@ -0,0 +1,6 @@ +APPLICATION = thread_msg_avail +include ../Makefile.tests_common + +DISABLE_MODULE += auto_init + +include $(RIOTBASE)/Makefile.include diff --git a/tests/thread_msg_avail/main.c b/tests/thread_msg_avail/main.c new file mode 100644 index 0000000000..39adaaa687 --- /dev/null +++ b/tests/thread_msg_avail/main.c @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2015 Nick van IJzendoorn + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @ingroup tests + * @{ + * + * @file + * @brief Thread test application + * + * @author Nick van IJzendoorn + * + * @} + */ + +#include +#include + +#include "thread.h" +#include "msg.h" + +#define MSG_QUEUE_LENGTH (8) + +msg_t msg_queue[MSG_QUEUE_LENGTH]; + +int main(void) +{ + msg_t msges[MSG_QUEUE_LENGTH]; + + msg_init_queue(msg_queue, MSG_QUEUE_LENGTH); + + for (int idx = 0; idx < MSG_QUEUE_LENGTH; ++idx) { + msges[idx].sender_pid = thread_getpid(); + msges[idx].type = idx; + + msg_send_to_self(msges + idx); + + printf("Add message %d\n", idx); + + while (msg_avail() != (idx) + 1) + ; /* spin forever if we don't have the result we expect */ + } + + for (int idx = msg_avail(); idx > 0; --idx) { + msg_t msg; + msg_receive(&msg); + + printf("Receive message: %d\n", (MSG_QUEUE_LENGTH - idx)); + + while (msg.type != (MSG_QUEUE_LENGTH - idx) || msg_avail() != idx - 1) + ; /* spin forever if we don't have the result we expect */ + } + + puts("TEST PASSED\n"); + return 0; +}