FreeRTOS 以及一名写入者和两名读取者之间的同步

发布于 2025-01-09 06:24:39 字数 596 浏览 3 评论 0原文

我正在开发 Modbus 数据记录器,它有两个 RS-485 端口,由两个任务 modbus_0_taskmodbus_1_task 处理。这两个任务都使用共享的 data_descriptors 数组(仅用于读取)。这些任务下面将被称为“读者”。

还有另一个任务 config_keeper_task 更新 data_descriptors 数组(读取和写入)。下面将这个任务称为“writer”。

目前,我有单个互斥锁,可以保护 data_descriptors 数组不被超过 1 个任务访问。

一切都很好,但有一个副作用。当一个“读者”获取互斥锁时,另一个“读者”必须等待。这是没有必要的。他们只应该在“作者”有权访问时等待。

我该如何解决这个问题?

我正在考虑对最大值和初始值2的信号量进行计数。

两个读取器读取一次,所以我的数组可以同时被两个读取器读取。

作者两次获取信号量(并等待所有读者完成)。当它完成时 - 它给出信号量 2 次。

这是执行此操作的正常方法吗?

I'm working on Modbus data logger that has two RS-485 ports handled by two tasks modbus_0_task and modbus_1_task. Both tasks use shared data_descriptors array (only for reading). These tasks will be called "readers" below.

There is also another task config_keeper_task that updates data_descriptors array (read and write). This task will be called "writer" below.

At this moment I have single mutex that protects data_descriptors array from being accessed by more than 1 task.

Everything works fine, but there is one side effect. When one "reader" takes mutex - another "reader" has to wait. This is not necessary. They only should wait when the "writer" has access.

How can I fix this?

I was thinking about counting semaphore with maximum and initial value 2.

Two readers take once, so my array could be read by both at the same time.

Writer take semaphore two times (and also waits until all readers finish). When it finishes - it gives semaphore 2 times.

Is this the normal way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幻想少年梦 2025-01-16 06:24:39

因此,经过几次实验和一些研究,我知道我需要读/写锁模式,并且有两种类型的简单读/写锁适合 FreeRTOS。

首先可以用更少的资源来实现:1 个互斥体和 1 个信号量。当读者和作者同时需要访问时,读者拥有优先权

第二个需要更多:2 个互斥体和 2 个信号量。 写入者具有优先权,读取者必须等待写入者完成(实际上是所有写入者,因为超过 1 个写入者可以等待访问)。

我发现很少有为 FreeRTOS 编写的实现,并且(为了充分理解它是如何工作的)我已经完全重写了它以适合我的项目。

这是我最喜欢的 Michael Becker 实现:

https: //github.com/michaelbecker/freertos-addons/blob/master/c/Source/read_write_lock.c

So after few experiments and some research I know that I need read/write lock pattern, and there are 2 types of simple r/w locks suitable for FreeRTOS.

First can be implemented with less resources: 1 mutex and 1 semaphore. Reader has priority when the reader and writer need access at the same time.

Second requires a bit more: 2 mutex and 2 semaphores. Writer has priority and readers must wait until writer finishes (actually all writers, because more than 1 writer can wait for access).

I found few implementations written for FreeRTOS and (to have full understanding how it works) I have rewritten this completely to fit my project.

Here is the my favourite implementation by Michael Becker:

https://github.com/michaelbecker/freertos-addons/blob/master/c/Source/read_write_lock.c

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文