1 /*
2 * Copyright (c) 2025 Instituto Superior de Engenharia do Porto (ISEP).
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/kernel.h>
8
9 #define BUF_SIZE 10
10 #define INACTIVE -1
11 #define PRIORITY 5
12
13 K_MSGQ_DEFINE(my_msgq, sizeof(char), BUF_SIZE, 1);
14
producer_function(void * rec,void * p2,void * p3)15 void producer_function(void *rec, void *p2, void *p3)
16 {
17 k_tid_t receiving_thread = (k_tid_t) rec;
18
19 char normal_data = '0';
20 char urgent_data = 'A';
21 int total_sent = 0;
22
23 /*
24 * sends messages every 100 msec, in repeating
25 * sequence: normal, normal, urgent, ...
26 */
27 while (total_sent < (BUF_SIZE - 1)) {
28 for (int i = 0; i < 2; i++) {
29 printk("[producer] sending: %c\n", normal_data);
30 k_msgq_put(&my_msgq, &normal_data, K_NO_WAIT);
31 k_sleep(K_MSEC(100));
32 normal_data++;
33 }
34 printk("[producer] sending: %c (urgent)\n", urgent_data);
35 k_msgq_put_front(&my_msgq, &urgent_data);
36 k_sleep(K_MSEC(100));
37 urgent_data++;
38
39 total_sent += 3;
40 }
41
42 /*
43 * finished sending messages, now start the receiving thread.
44 * keep in mind both threads can be running at the same time,
45 * but in this example we wish to see the queue accumulate some
46 * messages before the receiver thread starts reading them out.
47 */
48 k_thread_start(receiving_thread);
49 }
50
consumer_function(void * p1,void * p2,void * p3)51 void consumer_function(void *p1, void *p2, void *p3)
52 {
53 char received[BUF_SIZE];
54
55 for (int i = 0; i < (BUF_SIZE - 1); i++) {
56 k_msgq_get(&my_msgq, &received[i], K_NO_WAIT);
57 }
58
59 received[BUF_SIZE - 1] = '\0';
60 /* we expect to see CBA012345... */
61 printk("[consumer] got sequence: %s\n", received);
62 }
63
64 K_THREAD_DEFINE(consumer_thread, 2048, consumer_function,
65 NULL, NULL, NULL, PRIORITY, 0, INACTIVE);
66
67 K_THREAD_DEFINE(producer_thread, 2048, producer_function,
68 ((void *) consumer_thread), NULL, NULL, PRIORITY, 0, 0);
69