Files
2026-10-19 23:09:38 -07:00

74 lines
2.1 KiB
C

#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>
// Thread A: higher priority
#define THREAD_A_STACK_SIZE 512
#define THREAD_A_PRIORITY 2
// Thread B: lower priority
#define THREAD_B_STACK_SIZE 512
#define THREAD_B_PRIORITY 10
// Allocate stack memory for Thread A
K_THREAD_STACK_DEFINE(thread_a_stack, THREAD_A_STACK_SIZE);
// Thread A control structure and thread ID
struct k_thread thread_a_data;
k_tid_t thread_a_id;
// Define the FIFO message structure
struct my_msg {
void *reserved; // Required by Zephyr FIFO for internal linkage
int tata;
int titi;
};
// Define and initialize a FIFO queue
K_FIFO_DEFINE(my_fifo);
// Thread A: allocate and send a message through FIFO
void thread_a_entry(void *p1, void *p2, void *p3) {
// Dynamically allocate memory for the message
struct my_msg *msg = k_malloc(sizeof(struct my_msg));
// Check for allocation failure
if (msg == NULL) {
printk("Message allocation failed\n");
return;
}
// Populate the message fields
msg->tata = 42;
msg->titi = 100;
printk("Thread A: Sending tata=%d titi=%d\n", msg->tata, msg->titi);
// Enqueue the message pointer and transfer ownership to FIFO
k_fifo_put(&my_fifo, msg);
}
// Thread B: receive and process a message from FIFO
void thread_b_entry(void *p1, void *p2, void *p3) {
// Block until a message becomes available
struct my_msg *msg = k_fifo_get(&my_fifo, K_FOREVER);
// Print the received message
printk("Thread B: Received tata=%d titi=%d\n", msg->tata, msg->titi);
// Release dynamically allocated memory after processing
k_free(msg);
}
int main(void) {
// Create and start Thread A dynamically at runtime
thread_a_id =
k_thread_create(&thread_a_data,
thread_a_stack,
K_THREAD_STACK_SIZEOF(thread_a_stack),
thread_a_entry, NULL, NULL, NULL,
THREAD_A_PRIORITY, 0, K_NO_WAIT);
// Suppress unused variable warnings
ARG_UNUSED(thread_a_id);
return 0;
}
// Define Thread B statically and start it during system initialization
K_THREAD_DEFINE(thread_b_id,
THREAD_B_STACK_SIZE,
thread_b_entry, NULL, NULL, NULL,
THREAD_B_PRIORITY, 0, 0);