我有2个生产者和1个消费者使用单个fifo。邮件使用k_fifo_alloc_put
入队,如下所示:
#include <zephyr.h>
struct message_t {
u32_t info;
};
K_FIFO_DEFINE(fifo);
void thread_func(void *arg1, void *arg2, void *arg3)
{
ARG_UNUSED(arg1);
ARG_UNUSED(arg2);
ARG_UNUSED(arg3);
while(1) {
struct message_t msg = {
.info = 1,
};
k_fifo_alloc_put(&fifo, &msg);
k_sleep(K_SECONDS(1));
}
}
K_THREAD_STACK_DEFINE(thread1_stack_area, 256);
static struct k_thread thread1_data;
void tick_handler(struct k_timer *timer)
{
struct message_t msg = {
.info = 2,
};
k_thread_system_pool_assign(k_current_get());
k_fifo_alloc_put(&fifo, &msg);
}
void main(void)
{
k_thread_system_pool_assign(k_current_get());
k_thread_create(&thread1_data, thread1_stack_area,
K_THREAD_STACK_SIZEOF(thread1_stack_area),
thread_func,
NULL, NULL, NULL,
7, 0, K_NO_WAIT);
struct k_timer timer;
k_timer_init(&timer, tick_handler, NULL);
k_timer_start(&timer, K_SECONDS(1), K_SECONDS(1));
struct message_t *msg;
for(;;) {
msg = k_fifo_get(&fifo, K_FOREVER);
if(msg) printk("Received message from fifo: %d\r\n", msg->info);
}
}
两个生产者都从同一个堆中进行分配。计时器使用k_thread_system_pool_assign(k_current_get());
明确地将系统堆分配给自身,第二个线程从main继承相同的堆。
这样做安全吗?如果没有,我应该如何实施这种行为?
我在这里真正不了解的是k_fifo_alloc_put
是如何执行分配的,以及如何如接口文档中所述在检索时释放此资源:
k_fifo_alloc_put(fifo,数据):
此例程将数据项添加到@a fifo。有一个隐含的 来自调用线程的资源池的内存分配,即 删除项目后自动释放。