RTThread concurrent display method based on priority inheritance and double buffering
By using priority inheritance and the RTThread concurrent display method with double buffering, the problems of priority inversion, frame tearing, and network disconnection in RTOS are solved, achieving smooth screen refresh and effective display, and improving system stability and user experience.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- SHANGHAI LINGZE INFORMATION TECH CO LTD
- Filing Date
- 2026-05-21
- Publication Date
- 2026-07-10
Smart Images

Figure CN122363646A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of embedded real-time operating system (RTOS) technology, specifically to an RTThread concurrent display method based on priority inheritance and double buffering. Background Technology
[0002] IoT gas sensing terminal devices are typically equipped with displays to show real-time sensor data such as CO2, temperature, humidity, and VOCs, while simultaneously receiving downlink control commands from the server via the MQTT protocol. Existing technologies implementing this functionality on RTOS such as RTThread face the following four technical challenges:
[0003] (1) Priority inversion causes display stuttering: The display refresh task (high priority PH) and the downlink instruction parsing task (low priority PL) share a mutex lock that protects the display state. When the PL task holds the lock, the PH task is blocked while waiting for the lock; if a medium-priority PM task (such as network transceiver) preempts the PL task at this time, the PH task will continue to wait, and the blocking time can exceed 100ms, resulting in visible stuttering of the display refresh. The ordinary rt_mutex implementation of RTThread supports priority inheritance, but the existing application code does not use it correctly, resulting in the continued existence of the priority inversion problem.
[0004] (2) Frame buffer write-read contention leads to display tearing: The existing solution uses a single frame buffer. The data update thread and the display drive thread access the frame buffer at the same time. When data is updated in the middle of displaying a frame of data, the upper half of the screen displays the old data and the lower half displays the new data, resulting in visual tearing and poor user experience.
[0005] (3) Downlink command blocks UI thread: Flash write operation (about 50ms) is executed synchronously in display refresh task, which causes the display refresh to be blocked for 50ms each time a configuration-type downlink command is received. When multiple commands arrive in succession, the cumulative blocking time is even longer.
[0006] (4) No degradation strategy when the network is disconnected: In the existing solution, the display screen stops updating after the MQTT connection is disconnected and enters a black screen or crash state. Users cannot know the current status of the device, which brings difficulties to on-site operation and maintenance. Summary of the Invention
[0007] The purpose of this invention is to provide a concurrent display method for RTThread based on priority inheritance and double buffering, so as to solve the problems mentioned in the background art.
[0008] To achieve the above objectives, the present invention provides the following technical solution: a concurrent display method for RTThread based on priority inheritance and double buffering, running on an IoT terminal device equipped with an RTThread real-time operating system and a display screen, comprising the following steps:
[0009] (1) Create a high-priority display refresh task PH and a low-priority downlink instruction parsing task PL, and PH > PL; use the rt_mutex_t priority inheritance mutex of RTThread to protect the display state shared data area. When the low-priority instruction parsing task holds the mutex, the RTThread scheduler temporarily raises its priority to the highest priority thread level waiting for the lock. After the lock is released, the original priority PL is restored to eliminate priority inversion.
[0010] (2) Maintain a double-frame buffer structure, which includes a frame buffer array frame_buf[2][] and a single-byte active buffer index active_idx; the display driver always reads frame_buf[active_idx] for display, and the data update operation is written to the inactive buffer frame_buf[1-active_idx]; in the Vsync vertical synchronization interrupt service routine, active_idx is atomically swapped through a single-byte write operation to eliminate frame tearing;
[0011] (3) The downlink instruction receiving callback only writes the instruction data into the RTThread message queue rt_mq_t in a non-blocking manner. The independent instruction execution task is dequeued from the message queue and performs Flash writing, acquisition task parameter update notification time-consuming operations to achieve decoupling between the display refresh task and the instruction execution task;
[0012] (4) Maintain a four-state network state machine including ONLINE, OFFLINE, RECONNECT, and ERROR. The state transition is driven by MQTT connection events and communication module state events. Each state corresponds to a dedicated display screen to display content, ensuring that the display screen can effectively display under any network conditions.
[0013] (5) Construct a dynamic priority inheritance and hierarchical mutual exclusion lock system: Based on the thread load and lock contention frequency, dynamically calculate the inheritance priority threshold, divide the shared data area into a lock-free read-only area, a lightweight mutual exclusion read-write area, and a heavyweight mutual exclusion read-write area, and match the three-level differentiated lock access mechanism.
[0014] Configure three sets of frame buffer units with status markers, establish closed-loop buffer flow logic, dynamically adjust the frame rate based on data update frequency, network status, and resolution, and perform pixel-level local incremental refresh.
[0015] Preferably, the double-buffered atomic swap in step (2) is executed in the Vsync interrupt service routine. Specifically, it is implemented as follows: before entering the critical section, rt_hw_interrupt_disable() is called to disable the interrupt, active_idx=1-active_idx single-byte assignment operation is performed, and then rt_hw_interrupt_enable() is called to restore the interrupt; the critical section protection time does not exceed 3 CPU instruction cycles.
[0016] Preferably, in step (3), the downlink instructions are divided into configuration instructions and control instructions; the configuration instructions are written to Flash persistent storage and the acquisition task is notified to update parameters through the RTThread event set rt_event_t, while the control instructions are executed by directly calling the driver interface; the instruction execution time is reduced from a uniform 50ms to about 1ms for control instructions.
[0017] Preferably, step (4) also includes a frame rate adaptive adjustment mechanism: In ONLINE state, when the sensor data update frequency is higher than the display refresh rate, the display refreshes at a maximum frame rate of ≤60fps; when the data update frequency is lower than the display maximum frame rate, only data changes trigger the refresh, and the display is in low-power standby mode at other times; in OFFLINE state, the display refresh rate drops to 1fps.
[0018] Preferably, in step (3), the capacity of the rt_mq_t message queue is no less than 16 instruction messages. When the queue is full, non-urgent instructions are discarded and logged. Urgent instructions are processed through an independent high-priority emergency queue with a capacity of 2 messages.
[0019] Preferably, the shared data area in step (1) displays the current gas concentration values, alarm status flags, network connection status, device running time, and the last successful reporting timestamp; the total number of bytes in the shared data area does not exceed 256 bytes, and the read / write operation time during the holding period of the mutex lock does not exceed 1 millisecond.
[0020] Preferably, in step (5), the downlink instructions are checked for legality, timeliness, and adaptability before execution, a three-level instruction queue with weighted allocation is constructed, and an instruction execution timeout adaptive termination rule is set.
[0021] A six-state machine is driven by network connection / weak network / offline / reconnection / failure / recovery events. When the network is disconnected, data is cached and displayed in a time-gradient layer, and maintenance prompts are automatically generated.
[0022] The system monitors thread health from two dimensions, establishes a tiered self-healing strategy for anomalies, and dynamically adjusts the power consumption of the display module based on the display load.
[0023] An enhanced method for concurrent display of RTThread based on priority inheritance and double buffering, with three-frame buffer dynamic scheduling and high-resolution adaptation: three sets of frame buffers are used to replace double buffering, and with the buffer status flag, the atomic switching of the three-buffer index is completed in the Vsync interrupt, supporting dynamic resolution adaptation.
[0024] Three-level instruction priority scheduling and pre-verification filtering: Downlink instructions are divided into three levels: normal, important, and urgent. Legality pre-verification is performed before instruction execution, and instructions that time out are automatically terminated.
[0025] Display partial incremental refresh and multi-level caching when the network is offline: Only the display blocks with data changes are refreshed, and multiple frames of valid display data are cached in a time gradient when the network is offline;
[0026] Hierarchical mutex locks and lock-free read-only areas: The shared area is divided into read-only areas and read-write areas. Read-only areas are accessed without locks, while read-write areas use hierarchical mutex locks.
[0027] Dual-threaded exception self-recovery: Real-time monitoring and display of the command thread status, automatic restart or rollback in case of exception.
[0028] Preferably, the dynamic scheduling of the three-frame buffer is as follows: configure three groups of buffers frame_buf[3][] and mark them as idle, ready, and display states; write data updates to the idle buffer and mark it as ready after completion; in the Vsync interrupt, the index is switched atomically in the order of idle → ready → display, supporting high resolution display of 480×800 and above, without tearing or buffer waiting;
[0029] The three-level instruction priority scheduling is as follows: ordinary instructions are placed in the regular queue, important instructions are placed in the priority queue, and urgent instructions are placed in the highest priority queue; the scheduling priority is urgent > important > ordinary; before the instruction is executed, the parameters and device status are checked, and invalid instructions are filtered to reduce meaningless Flash writing.
[0030] The automatic termination of instructions upon timeout is as follows: the timeout threshold for Flash write instructions is set to 30ms, and for control instructions it is set to 0.5ms; if the timeout is not completed, execution will be terminated immediately, an exception log will be recorded, and subsequent instruction scheduling will not be blocked.
[0031] Preferably, the partial incremental refresh of the display screen specifically involves: maintaining the hash value of the display data of the previous frame, refreshing only the local blocks where the hash value has changed, reducing the data refresh amount by more than 70%; in offline mode, caching 3 sets of display data according to time gradients of 1s, 5s, and 30s, and smoothly switching to real-time data after the network is restored;
[0032] The hierarchical mutex lock and lock-free read-only area are as follows: the read-only data area adopts atomic read lock-free access; the read-write data area adopts two-level mutex locks, with the explicit task lock having higher priority than the instruction task lock, reducing the probability of lock conflict by more than 90%;
[0033] The dual-threaded exception self-recovery is specifically as follows: the RTThread thread watchdog monitors the display and command tasks; if the thread fails to feed the watchdog for a timeout, an exception is determined, the display thread automatically switches to the backup buffer and restarts, and the command thread rolls back unpersisted instructions and restarts the task.
[0034] Compared with the prior art, the beneficial effects of the present invention are:
[0035] This solution provides a concurrent display method for RTThread based on priority inheritance and double buffering, which can eliminate technical problems such as priority inversion, frame tearing, UI blocking, and black screen.
[0036] Correctly utilize the priority inheritance feature of RTThreadrt_mutex_t to eliminate priority inversion; design a double-frame buffer structure and Vsync interrupt atomic exchange mechanism to eliminate frame tearing; asynchronously decouple downlink instruction processing to an independent execution thread through rt_mq_t message queue to eliminate UI blocking; design a four-state network state machine to ensure effective display under any network conditions.
[0037] (1) The display refresh latency has been reduced from more than 100ms to less than 5ms, improving refresh smoothness by more than 20 times;
[0038] (2) Frame tearing is completely eliminated;
[0039] (3) Downlink instruction processing (including Flash writing) no longer affects the UI refresh cycle;
[0040] (4) The display screen can display effective content under any network condition, which improves the efficiency of on-site operation and maintenance.
[0041] Dynamic priority inheritance combined with hierarchical mutexes completely eliminates priority inversion and lock contention stuttering, shortening thread waiting time and improving system scheduling efficiency. Intelligent triple buffering and pixel-level incremental refresh eliminate display tearing and stuttering, dynamic frame rate adapts to multiple scenarios, and high-resolution displays have no buffering wait, significantly improving display smoothness.
[0042] Highly efficient instruction processing includes pre-verification filtering of invalid operations, multi-level weighted queues ensuring priority execution of urgent instructions, and adaptive timeout termination to avoid thread blocking, thus improving instruction execution efficiency. Enhanced network adaptability features include a six-state network state machine, progressive network disconnection caching, uninterrupted display across all network scenarios, and automatic generation of maintenance prompts, significantly improving device availability and on-site maintenance efficiency.
[0043] System stability and power consumption optimization, dual-thread collaborative self-healing significantly reduce system failure rate, low-power display management achieves a balance between performance and battery life, and the device operates more stably over the long term. Attached Figure Description
[0044] Figure 1 This is a schematic diagram illustrating the anti-tearing mechanism of dual-frame buffer atomic exchange in this invention;
[0045] Figure 2 This is a schematic diagram of the four-state network state machine of the present invention. Detailed Implementation
[0046] Please see Figure 1-2 The present invention provides the following technical solution:
[0047] The RTThread concurrent display method based on priority inheritance and double buffering runs on IoT terminal devices equipped with the RTThread real-time operating system and display screen, and includes the following steps:
[0048] (1) Create a high-priority display refresh task PH and a low-priority downlink instruction parsing task PL, and PH > PL; use the rt_mutex_t priority inheritance mutex of RTThread to protect the display state shared data area. When the low-priority instruction parsing task holds the mutex, the RTThread scheduler temporarily raises its priority to the highest priority thread level waiting for the lock. After the lock is released, the original priority PL is restored to eliminate priority inversion.
[0049] The status shared data area displayed in step (1) includes the current gas concentration values, alarm status flags, network connection status, device running time, and the last successful reporting timestamp; the total number of bytes in the shared data area does not exceed 256 bytes, and the read and write operation time during the holding period of the mutex lock does not exceed 1 millisecond.
[0050] (2) Maintain a double-frame buffer structure, which includes a frame buffer array frame_buf[2][] and a single-byte active buffer index active_idx; the display driver always reads frame_buf[active_idx] for display, and writes the data update operation to the inactive buffer frame_buf[1-active_idx]; in the Vsync vertical synchronization interrupt service routine, active_idx is atomically swapped through a single-byte write operation to eliminate frame tearing;
[0051] In step (2), the double-buffered atomic swap is executed in the Vsync interrupt service routine. Specifically, before entering the critical section, rt_hw_interrupt_disable() is called to disable interrupts, active_idx=1-active_idx single-byte assignment operation is performed, and then rt_hw_interrupt_enable() is called to restore interrupts. The critical section protection time does not exceed 3 CPU instruction cycles.
[0052] (3) The downlink instruction receiving callback only writes the instruction data into the RTThread message queue rt_mq_t in a non-blocking manner. The independent instruction execution task is dequeued from the message queue and performs Flash writing, acquisition task parameter update notification time-consuming operations to achieve decoupling between the display refresh task and the instruction execution task;
[0053] In step (3), the downlink instructions are divided into configuration instructions and control instructions. Configuration instructions are written to Flash persistent storage and the acquisition task is notified to update parameters through the RTThread event set rt_event_t. Control instructions are executed by directly calling the driver interface. The instruction execution time is reduced from about 50ms to about 1ms for control instructions.
[0054] In step (3), the capacity of the rt_mq_t message queue is no less than 16 instruction messages. When the queue is full, non-urgent instructions are discarded and logged. Urgent instructions are processed through an independent high-priority emergency queue with a capacity of 2 messages.
[0055] (4) Maintain a four-state network state machine including ONLINE, OFFLINE, RECONNECT, and ERROR. The state transition is driven by MQTT connection events and communication module state events. Each state corresponds to a dedicated display screen to display content, ensuring that the display screen can effectively display under any network conditions.
[0056] Step (4) also includes a frame rate adaptive adjustment mechanism: In ONLINE state, when the sensor data update frequency is higher than the display refresh rate, the display refreshes at a maximum frame rate of ≤60fps. When the data update frequency is lower than the display maximum frame rate, only data changes trigger a refresh, and the display is in low-power standby mode at other times. In OFFLINE state, the display refresh rate drops to 1fps.
[0057] Step (5) Dynamic priority inheritance and hierarchical mutex optimization:
[0058] S1, Construct a dynamic priority inheritance and hierarchical mutex lock system: Based on thread load and lock contention frequency, dynamically calculate the inheritance priority threshold, and divide the shared data area into a lock-free read-only area, a lightweight mutex read-write area, and a heavyweight mutex read-write area, matching a three-level differentiated lock access mechanism; the dynamic priority inheritance threshold is calculated as inheritance priority = basic explicit priority - lock contention frequency coefficient × thread load rate; lightweight mutex locks use spin waiting, and heavyweight mutex locks use blocking waiting to reduce the probability of lock conflict.
[0059] S2 establishes an intelligent triple-buffer, dynamic frame rate collaborative scheduling architecture: it configures three sets of frame buffer units with status markers, establishes closed-loop buffer flow logic, and dynamically adjusts the frame rate based on data update frequency, network status, and resolution, performing pixel-level local incremental refresh; the three sets of frame buffers are marked as idle / ready / display states, and flow in a closed loop according to idle → ready → display → idle; local incremental refresh is achieved through pixel block hash comparison, reducing the amount of data refreshed, and the dynamic frame rate adaptive range is 1-120fps.
[0060] S3 enables instruction pre-verification and intelligent scheduling of multi-level weighted queues: it performs pre-verification of the legality, timeliness, and adaptability of downlink instructions, constructs a three-level instruction queue with weighted allocation, and sets an adaptive termination rule for instruction execution timeout; the three-level instruction queue is weighted according to urgency > importance > normal, the timeout threshold is dynamically set according to the instruction type, and the abnormal reporting and data rollback are automatically triggered after the instruction is terminated.
[0061] S4 establishes a six-state network intelligent display and a progressive caching mechanism for network outages: the six-state state machine is driven by network connection / weak network / offline / reconnection / fault / recovery events. When the network is out of service, the display data is cached in a time gradient and the operation and maintenance prompts are automatically generated. The six-state network state machine covers the entire network scenario. When the network is out of service, four sets of display data are cached in a gradient of 1s / 10s / 60s / 300s. After the network is restored, the display content is smoothly switched in time sequence.
[0062] S5 features dual-thread collaborative self-healing and low-power display management: dual-dimensional monitoring of thread health, establishment of a graded abnormal self-healing strategy, and dynamic adjustment of display module power consumption based on display load; thread health is determined by two dimensions: execution cycle deviation and watchdog timeout, and abnormal self-healing is divided into three levels: thread restart, data rollback, and buffer switching; display power consumption is adjusted in conjunction with backlight and refresh rate, resulting in a significant reduction in power consumption.
[0063] The working principle of dynamic priority inheritance and hierarchical mutex locks: The system collects thread load rate and lock contention frequency in real time, and dynamically calculates the priority inheritance threshold through an algorithm to avoid the waste of resources by fixed inheritance; the displayed shared data is partitioned according to access characteristics, with direct atomic access to the lock-free read-only area, fast access via spin lock in the lightweight mutex area, and blocking to ensure safety in the heavyweight mutex area. The three-level locks work together to reduce conflicts; dynamic priority ensures that high-priority display threads are not preempted by medium-priority threads.
[0064] The three frame buffers are responsible for data writing, data preparation, and screen display functions respectively, and flow in a closed loop of idle → ready → display → idle to completely avoid read and write contention; the system collects data update frequency, network status, and resolution in real time and automatically matches the optimal frame rate; it identifies changed areas by comparing pixel block hashes and only refreshes the changed pixel blocks to reduce data transmission and computation overhead.
[0065] Downlink instructions first undergo parameter validity, execution timeliness, and device compatibility checks to filter out invalid instructions; they are then assigned weights based on urgency and execution time and placed into a three-level queue, with higher-weight instructions scheduled first; instruction execution time is monitored in real time, and execution is terminated immediately upon reaching a dynamic threshold, triggering rollback and exception reporting to avoid single instructions blocking the scheduling process.
[0066] The network status is driven by connection signal, reconnection count, and fault code to switch between six states, with each state matching exclusive display content; after a network outage, data is cached and displayed in layers according to time gradients, retaining valid information for multiple time periods; when the network is restored, it switches smoothly in time order to avoid display jumps, and at the same time automatically generates fault codes and maintenance prompts.
[0067] An enhanced method for concurrent display of RTThread based on priority inheritance and double buffering, with dynamic scheduling and high-resolution adaptation using three-frame buffers: three sets of frame buffers are used to replace double buffering, and with the buffer status flag, the atomic switching of the three-buffer index is completed in the Vsync interrupt, supporting dynamic resolution adaptation;
[0068] Three-level instruction priority scheduling and pre-verification filtering: Downlink instructions are divided into three levels: normal, important, and urgent. Legality pre-verification is performed before instruction execution, and instructions that time out are automatically terminated.
[0069] Display partial incremental refresh and multi-level caching when the network is offline: Only the display blocks with data changes are refreshed, and multiple frames of valid display data are cached in a time gradient when the network is offline;
[0070] Hierarchical mutex locks and lock-free read-only areas: The shared area is divided into read-only areas and read-write areas. Read-only areas are accessed without locks, while read-write areas use hierarchical mutex locks.
[0071] Dual-threaded exception self-recovery: Real-time monitoring and display of the command thread status, automatic restart or rollback in case of exception.
[0072] The three-frame buffer dynamic scheduling is as follows: Configure three groups of buffers frame_buf[3][] and mark them as idle, ready and display states; data update is written to the idle buffer and marked as ready after completion; in the Vsync interrupt, the index is switched atomically in the order of idle → ready → display, supporting high-resolution display of 480×800 and above, without tearing or buffer waiting;
[0073] The three-level instruction priority scheduling is as follows: ordinary instructions are placed in the regular queue, important instructions are placed in the priority queue, and urgent instructions are placed in the highest priority queue. The scheduling priority is urgent > important > ordinary. Before the instruction is executed, the parameters and device status are checked, and invalid instructions are filtered to reduce meaningless Flash writes.
[0074] Automatic termination upon instruction timeout: The timeout threshold for Flash write instructions is set to 30ms, and for control instructions it is set to 0.5ms; if the instruction is not completed within the timeout period, execution will be terminated immediately, an exception log will be recorded, and subsequent instruction scheduling will not be blocked.
[0075] The partial incremental refresh of the display screen is as follows: maintain the hash value of the display data of the previous frame, refresh only the local blocks where the hash value has changed, and reduce the amount of data refresh by more than 70%; in offline state, cache 3 sets of display data according to the time gradient of 1 second, 5 seconds and 30 seconds, and smoothly switch to real-time data after the network is restored;
[0076] The hierarchical mutex lock and lock-free read-only area are as follows: the read-only data area adopts atomic read lock-free access; the read-write data area adopts two-level mutex locks, with the explicit task lock having higher priority than the instruction task lock, reducing the probability of lock conflict by more than 90%;
[0077] The dual-thread exception self-recovery mechanism works as follows: the RTThread thread watchdog monitors the display and command tasks; if the thread fails to feed the watchdog and times out, an exception is determined. If the display thread is abnormal, the backup buffer is automatically switched and restarted. If the command thread is abnormal, unpersisted commands are rolled back and the task is restarted.
[0078] The foregoing has shown and described the basic principles, main features, and advantages of the present invention. It will be apparent to those skilled in the art that the present invention is not limited to the details of the above exemplary embodiments, and that the present invention can be implemented in other specific forms without departing from the spirit or basic characteristics of the present invention. Therefore, the embodiments should be regarded as exemplary and non-limiting in all respects. The scope of the present invention is defined by the appended claims rather than the foregoing description, and therefore all changes falling within the meaning and scope of the equivalents of the claims are intended to be included within the present invention.
[0079] Example:
[0080] An IoT gas sensing terminal is equipped with the RTThread 4.1.0 operating system, a 240×240 resolution TFT screen, a Vsync frequency of 30Hz, and is connected to the MCU via the SPI bus; MQTT communication uses a 4G module.
[0081] The system creates a display refresh task (priority 10, refreshing one frame every 33ms) and an instruction parsing task (priority 3). A priority-inherited mutex is created using `rt_mutex_create(&display_mutex,RT_IPC_FLAG_PRIO)`. When the instruction parsing task (P3) holds the `display_mutex`, `RTThread` temporarily promotes it to P10 to prevent medium-priority tasks (P5~P9) from inserting and causing P10 to wait too long.
[0082] The framebuf array `frame_buf[2]
[57600] ` (240×240×1 bytes) is initially set to `active_idx=0`. When sensor data is updated, it is written to `frame_buf[1-active_idx]`. After writing, the following is executed in the Vsync interrupt: `__disable_irq();active_idx^=1;__enable_irq()`. The display driver transfers `frame_buf[active_idx]` to the screen via DMA, and the entire exchange process is free of data tearing.
[0083] When a downlink command is received (such as "modify CO alarm threshold to 50ppm"), the MQTT callback writes the command to rt_mq_send(&cmd_queue) and returns immediately; after the independent command execution task is dequeued, it is written to Flash (about 50ms), and the threshold parameter is updated by notifying the acquisition task through rt_event_send. The entire process does not block the display refresh task.
[0084] Timing comparison between priority inheritance mutex and ordinary mutex:
[0085] [Existing technical flaw: Priority inversion occurs in ordinary mutex locks]
[0086] At time 0: PL (P3) acquires the mutex and begins processing instructions.
[0087] Time 1: PH (P10) attempts to acquire the mutex → waits (blocked)
[0088] Time 2: PM (P7) preempts PL → PL is suspended, PH continues to wait.
[0089] Time 3: PM execution complete, PL resumes execution.
[0090] Moment 4: PL releases the mutex → PH acquires the mutex and begins refreshing.
[0091] →PH waiting time = PL execution time + PM execution time > 100ms ×.
[0092] [Optimization of this solution: rt_mutex_t priority inherits mutex lock]
[0093] At time 0: PL (P3) acquires the mutex, and RTThread temporarily promotes PL to P10.
[0094] Time 1: PH (P10) attempts to acquire the mutex → waits
[0095] Time 2: PM (P7) attempts to preempt → PL has been increased to P10, PM cannot preempt.
[0096] Time 3: PL (promoted to P10) completes execution quickly, releases the mutex, and priority is restored to P3.
[0097] Time 4: PH immediately acquires the mutex and begins refreshing.
[0098] →PH waiting time = PL critical section execution time ≈ 1ms✔.
[0099] Although embodiments of the invention have been shown and described, it will be understood by those skilled in the art that various changes, modifications, substitutions and alterations can be made to these embodiments without departing from the principles and spirit of the invention, the scope of which is defined by the appended claims and their equivalents.
Claims
1. A concurrent display method for RTThread based on priority inheritance and double buffering, characterized in that, The following steps are included in the process of running an IoT terminal device equipped with the RTThread real-time operating system and a display screen: (1) Create a high-priority display refresh task PH and a low-priority downlink instruction parsing task PL, and PH > PL; use the rt_mutex_t priority inheritance mutex of RTThread to protect the display state shared data area. When the low-priority instruction parsing task holds the mutex, the RTThread scheduler temporarily raises its priority to the highest priority thread level waiting for the lock. After the lock is released, the original priority PL is restored to eliminate priority inversion. (2) Maintain a double-frame buffer structure, which includes a frame buffer array frame_buf[2][] and a single-byte active buffer index active_idx; the display driver always reads frame_buf[active_idx] for display, and the data update operation is written to the inactive buffer frame_buf[1-active_idx]; in the Vsync vertical synchronization interrupt service routine, active_idx is atomically swapped through a single-byte write operation to eliminate frame tearing; (3) The downlink instruction receiving callback only writes the instruction data into the RTThread message queue rt_mq_t in a non-blocking manner. The independent instruction execution task is dequeued from the message queue and performs Flash writing, acquisition task parameter update notification time-consuming operations to achieve decoupling between the display refresh task and the instruction execution task; (4) Maintain a four-state network state machine including ONLINE, OFFLINE, RECONNECT, and ERROR. The state transition is driven by MQTT connection events and communication module state events. Each state corresponds to a dedicated display screen to display content, ensuring that the display screen can effectively display under any network conditions. (5) Construct a dynamic priority inheritance and hierarchical mutual exclusion lock system: Based on the thread load and lock contention frequency, dynamically calculate the inheritance priority threshold, divide the shared data area into a lock-free read-only area, a lightweight mutual exclusion read-write area, and a heavyweight mutual exclusion read-write area, and match the three-level differentiated lock access mechanism. Configure three sets of frame buffer units with status markers, establish closed-loop buffer flow logic, dynamically adjust the frame rate based on data update frequency, network status, and resolution, and perform pixel-level local incremental refresh.
2. The RTThread concurrent display method based on priority inheritance and double buffering as described in claim 1, characterized in that: In step (2), the double-buffered atomic swap is executed in the Vsync interrupt service routine. Specifically, before entering the critical section, rt_hw_interrupt_disable() is called to disable interrupts, active_idx=1-active_idx single-byte assignment operation is performed, and then rt_hw_interrupt_enable() is called to restore interrupts. The critical section protection time does not exceed 3 CPU instruction cycles.
3. The RTThread concurrent display method based on priority inheritance and double buffering as described in claim 1, characterized in that: In step (3), the downlink instructions are divided into configuration instructions and control instructions. Configuration instructions are written to Flash persistent storage and the acquisition task is notified to update parameters through the RTThread event set rt_event_t. Control instructions are executed by directly calling the driver interface. The instruction execution time is reduced from about 50ms to about 1ms for control instructions.
4. The RTThread concurrent display method based on priority inheritance and double buffering according to claim 1, characterized in that: Step (4) also includes a frame rate adaptive adjustment mechanism: In ONLINE state, when the sensor data update frequency is higher than the display refresh rate, the display refreshes at a maximum frame rate of ≤60fps. When the data update frequency is lower than the display maximum frame rate, only data changes trigger a refresh, and the display is in low-power standby mode at other times. In OFFLINE state, the display refresh rate drops to 1fps.
5. The RTThread concurrent display method based on priority inheritance and double buffering according to claim 1, characterized in that: In step (3), the capacity of the rt_mq_t message queue is no less than 16 instruction messages. When the queue is full, non-urgent instructions are discarded and logged. Urgent instructions are processed through an independent high-priority emergency queue with a capacity of 2 messages.
6. The RTThread concurrent display method based on priority inheritance and double buffering according to claim 1, characterized in that: The status shared data area displayed in step (1) includes the current gas concentration values, alarm status flags, network connection status, device running time, and the last successful reporting timestamp; the total number of bytes in the shared data area does not exceed 256 bytes, and the read and write operation time during the holding period of the mutex lock does not exceed 1 millisecond.
7. The RTThread concurrent display method based on priority inheritance and double buffering according to claim 1, characterized in that: In step (5), the downlink instructions are checked for legality, timeliness, and adaptability before execution, a three-level instruction queue with weighted allocation is constructed, and an adaptive termination rule for instruction execution timeout is set. A six-state machine is driven by network connection / weak network / offline / reconnection / failure / recovery events. When the network is disconnected, data is cached and displayed in a time-gradient layer, and maintenance prompts are automatically generated. The system monitors thread health from two dimensions, establishes a tiered self-healing strategy for anomalies, and dynamically adjusts the power consumption of the display module based on the display load.
8. The enhanced method for concurrent display of RTThreads based on priority inheritance and double buffering as described in claim 1, characterized in that: Three-frame buffer dynamic scheduling and high-resolution adaptation: Three sets of frame buffers are used to replace double buffering. With the help of buffer status marking, the atomic switching of the three-buffer index is completed in the Vsync interrupt, which supports dynamic resolution adaptation. Three-level instruction priority scheduling and pre-verification filtering: Downlink instructions are divided into three levels: normal, important, and urgent. Legality pre-verification is performed before instruction execution, and instructions that time out are automatically terminated. Display partial incremental refresh and multi-level caching when the network is offline: Only the display blocks with data changes are refreshed, and multiple frames of valid display data are cached in a time gradient when the network is offline; Hierarchical mutex locks and lock-free read-only areas: The shared area is divided into read-only areas and read-write areas. Read-only areas are accessed without locks, while read-write areas use hierarchical mutex locks. Dual-threaded exception self-recovery: Real-time monitoring and display of the command thread status, automatic restart or rollback in case of exception.
9. The enhanced method for concurrent display of RTThreads based on priority inheritance and double buffering as described in claim 7, characterized in that: The three-frame buffer dynamic scheduling is as follows: Configure three groups of buffers frame_buf[3][] and mark them as idle, ready and display states; data update is written to the idle buffer and marked as ready after completion; in the Vsync interrupt, the index is atomically switched in the order of idle → ready → display, supporting high-resolution display of 480×800 and above, without tearing or buffer waiting; The three-level instruction priority scheduling is as follows: ordinary instructions are placed in the regular queue, important instructions are placed in the priority queue, and urgent instructions are placed in the highest priority queue; the scheduling priority is urgent > important > ordinary; before the instruction is executed, the parameters and device status are checked, and invalid instructions are filtered to reduce meaningless Flash writing. The automatic termination of instructions upon timeout is as follows: the timeout threshold for Flash write instructions is set to 30ms, and for control instructions it is set to 0.5ms; if the timeout is not completed, execution will be terminated immediately, an exception log will be recorded, and subsequent instruction scheduling will not be blocked.
10. The enhanced method for concurrent display of RTThreads based on priority inheritance and double buffering as described in claim 7, characterized in that: The partial incremental refresh of the display screen is specifically as follows: maintain the hash value of the display data of the previous frame, refresh only the local blocks where the hash value changes, and reduce the amount of data refresh by more than 70%; in offline state, cache 3 sets of display data according to the time gradient of 1s, 5s and 30s, and smoothly switch to real-time data after the network is restored; The hierarchical mutex lock and lock-free read-only area are as follows: the read-only data area adopts atomic read lock-free access; the read-write data area adopts two-level mutex locks, with the explicit task lock having higher priority than the instruction task lock, reducing the probability of lock conflict by more than 90%; The dual-threaded exception self-recovery is specifically as follows: the RTThread thread watchdog monitors the display and command tasks; if the thread fails to feed the watchdog for a timeout, an exception is determined, the display thread automatically switches to the backup buffer and restarts, and the command thread rolls back unpersisted instructions and restarts the task.