A method and system for implementing task-cross accessible thread-local storage
Patent Information
- Application Number
- CN202611043502.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-14
- Publication Date
- 2026-10-20
- Estimated Expiration
- 2046-07-14
AI Technical Summary
[0009]为解决上述技术问题,本发明提供一种跨任务可访问的线程局部存储实现方法及系统,以克服现有技术中存在的无法跨任务访问、依赖动态内存分配、无MMU环境适配性差的技术缺陷
将所有任务的TLS数据连续存放,通过基地址加(任务ID×键数+键ID)×指针大小的公式直接定位任意任务任意键的存储单元,实现常数时间复杂度的跨任务访问,无需目标任务配合,崩溃后可直接读取TLS现场。本发明提供第一接口和第二接口,第一接口用于设置指定任务和指定键的TLS值,第二接口用于获取指定任务和指定键的TLS值,使调试工具、性能监控模块可在任务崩溃后读取其TLS数据,或在运行中采集任意任务的TLS状态。
Smart Images

Figure CN122547557B_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the field of embedded real-time operating system technology, specifically relating to a method and system for implementing cross-task accessible thread-local storage for MMU-less embedded real-time operating systems, so as to realize direct access to and unified lifecycle management of thread-local storage data for any task. Background Technology
[0002] Thread Local Storage (TLS) is a mechanism that allows each thread to have its own independent copy of variables. It is widely used in multithreaded programming to implement thread-safe global variables. In embedded real-time operating systems, TLS is crucial for modular design and data isolation.
[0003] The fundamental premise of existing thread-local storage mechanisms is to ensure that each task can only access its own set of local data. Therefore, their design focus is usually on the question of "how the current task saves its own copy of local variables". Existing technologies, such as CN106445656A (a method and apparatus for implementing thread-local storage), adopt a storage structure of independent TLS data blocks for each task. Each task maintains its own TLS table, accesses the current task's data indirectly through a global pointer, and dynamically allocates memory at runtime (when the task is created or used for the first time).
[0004] However, in MMU-less embedded RTOS environments, the TLS mechanism, which can only be accessed by the current task, has significant limitations: when the target task exits abnormally, enters a fault state, or needs to be observed and intervened by a debugging, monitoring, or management task, traditional TLS, because its access path is bound to the current task context, cannot directly read and correct data from the target task. This results in TLS, while possessing the advantage of "task-private," lacking the ability to be "observable and interventional," especially in scenarios such as crash scene preservation, runtime diagnostics, parent-child task collaborative initialization, and anomaly recovery. Existing TLS struggles to meet the dual requirements of determinism and debuggability for MMU-less embedded systems.
[0005] The existing technology has the following main drawbacks: First, cross-task access is not possible. Existing TLS implementations are all limited to access within the current task / thread, making it impossible to read TLS data to locate problems after a task crashes.
[0006] Second, it relies on dynamic memory allocation. Runtime may trigger malloc, which introduces uncertainty and the risk of memory fragmentation in real-time systems.
[0007] Third, it has poor adaptability to environments without an MMU. Existing solutions rely on an MMU or dedicated registers, which are not suitable for architectures without an MMU, such as ARM Cortex-M and RISC-V.
[0008] Therefore, providing a method and system for implementing thread-local storage that solves the above problems, enables direct cross-task access, zero dynamic memory allocation at runtime, and is applicable to MMU-less architectures, is a technical problem that urgently needs to be solved by those skilled in the art. Summary of the Invention
[0009] To address the aforementioned technical problems, this invention provides a method and system for implementing thread-local storage that is accessible across tasks, thereby overcoming the technical defects of existing technologies, such as inability to access across tasks, reliance on dynamic memory allocation, and poor adaptability to environments without an MMU.
[0010] This invention overcomes the aforementioned shortcomings by constructing a unified thread-local storage area with task identifiers and key identifiers as two-dimensional indexes and by using a linear address mapping method to achieve cross-task direct addressing with constant complexity.
[0011] The overall design concept of this invention is not to view TLS as scattered private variables embedded within each task, but rather to integrate all... The data is organized into a two-dimensional local storage system consisting of a task dimension and a key dimension. The task dimension distinguishes which task the data belongs to, while the key dimension distinguishes which category the data belongs to. Semantics. Any Values are not isolated but organized within a combined positioning relationship of "target task + key identifier". In this design, the system uses... As a unification storage area, with As a basis for line positioning, This serves as the basis for column location. Thus, each TLS value corresponds to a storage unit in a two-dimensional matrix. When accessing data within the current task itself, the corresponding unit can be located based on the current task identifier and the specified key identifier; when accessing data from other tasks, the target unit can also be located directly based on the target task identifier and the specified key identifier, without needing to switch to the target task context first.
[0012] Specifically, this invention allocates a contiguous memory region at system startup, using a two-dimensional matrix of task identifiers and key identifiers to store the thread-local storage data of all tasks. It directly locates the storage unit of any key for any task using an address calculation formula, and provides a cross-task access interface to support setting and retrieving the thread-local storage value of a specified task. Furthermore, this invention employs a one-time allocation strategy at startup, eliminating the uncertainty of dynamic memory allocation at runtime, and does not rely on the MMU or dedicated registers, making it suitable for... , Architectures without MMU.
[0013] Thus, this invention enables direct cross-task access to thread-local storage for the first time, supporting the reading of thread-local storage data to locate problems after a task crashes, and meeting the dual requirements of determinism and debuggability for MMU-less embedded systems.
[0014] According to one aspect of the present invention, a method for implementing thread-local storage that is accessible across tasks is provided, comprising the following steps: During the startup phase of the MMU-free embedded real-time operating system, a contiguous memory region is allocated once as a unified thread-local storage area based on the preset maximum number of tasks and the maximum number of keys. The unified thread-local storage area uses task identifiers as row indices and key identifiers as column indices. Each combination of task identifiers and key identifiers corresponds to a pointer-sized storage unit, which is used to store a thread-local storage value. Based on the task identifier and the key identifier of the target task, the storage unit of the target task under the specified key identifier is located by linear address mapping, so as to realize cross-task access to the thread-local storage value of any target task.
[0015] In another aspect, the present invention provides a thread-local storage system accessible across tasks, comprising: A unified storage module is used to allocate a contiguous memory region as a unified thread-local storage area once during the startup phase of the MMU-less embedded real-time operating system, based on a preset maximum number of tasks and a maximum number of keys. The unified thread-local storage area uses task identifiers as row indices and key identifiers as column indices. Each combination of task identifiers and key identifiers corresponds to a pointer-sized storage unit, which is used to store a thread-local storage value. The address mapping module is used to locate the storage unit of the target task under the specified key identifier through linear address mapping based on the task identifier and the key identifier of the target task, so as to realize cross-task access to the thread-local storage value of any target task.
[0016] Compared with the prior art, the present invention has the following beneficial effects: The TLS data of all tasks is stored contiguously. The storage unit for any key in any task can be directly located using the formula: base address + (task ID × number of keys + key ID) × pointer size. This achieves cross-task access with constant time complexity, without requiring the target task's cooperation. The TLS state can be directly read after a crash. This invention provides a first interface and a second interface. The first interface is used to set the TLS value of a specified task and a specified key, and the second interface is used to retrieve the TLS value of a specified task and a specified key. This allows debugging tools and performance monitoring modules to read the TLS data of a task after a crash or to collect the TLS state of any task during runtime.
[0017] During system initialization, all TLS memory is calculated and allocated based on the maximum number of tasks and keys (e.g., 32 tasks × 32 keys = 4KB, or 16 tasks × 16 keys = 1KB, or 64 tasks × 16 keys = 1KB). At runtime, malloc is completely avoided, eliminating memory fragmentation and real-time uncertainty, thus meeting the deterministic requirements of safety-critical systems. Memory usage is predictable, with zero dynamic allocation at runtime.
[0018] It does not rely on an MMU, page tables, or dedicated registers; all operations are purely software-based, making it suitable for MMU-less architectures such as ARM Cortex-M and RISC-V. Attached Figure Description
[0019] To more clearly illustrate the technical solutions in the embodiments of this application or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments recorded in this application. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0020] Figure 1 This is a schematic diagram of the overall architecture of the cross-task accessible thread-local storage system provided in this embodiment of the invention, showing the two core modules, the unified storage module and the address mapping module, and their interrelationship. Figure 2 The complete flow sequence diagram of the cross-task accessible thread-local storage method provided in the embodiments of the present invention shows the complete process from mechanism establishment, key allocation, access within the task, cross-task access to task exit cleanup; Figure 3 This is a schematic diagram of a two-dimensional matrix memory layout provided in an embodiment of the present invention, illustrating a unified storage area structure with task identifiers as row indexes and key identifiers as column indexes; Figure 4 The flowchart provided in this embodiment of the invention illustrates the steps of traversing the entire row of storage units and calling the destructor function to release resources. Detailed Implementation
[0021] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0022] The embodiments of this invention are written in a progressive manner.
[0023] Terminology Explanation To facilitate understanding of the technical solution of this invention, some technical terms appearing in the specification are explained as follows: Thread-local storage ( , This is a mechanism that allows each task (thread) to have an independent copy of a variable. Each task can have a private copy of the same global variable name, and tasks do not interfere with each other. In this invention, TLS values are stored in a unified storage area at pointer size.
[0024] Task identifier ( The task identifier is an integer number used in the operating system to uniquely identify a task (thread), assigned by the kernel during system initialization. In this invention, the task identifier is used as a row index of a two-dimensional matrix.
[0025] Key identifier ( ): Global variable identifiers in thread-local storage mechanisms, used to distinguish different Data objects (such as task identity information, network connection handles, temporary buffer pointers, etc.). Its function is similar to... In the standard The application first passes through A key is assigned to obtain a unique ID, which can then be used to independently store and retrieve values in each task (i.e., each task maintains a private copy of the data for the same key). In this invention, the key identifier is used as a column index for a two-dimensional matrix.
[0026] Each task has a set of pre-defined keys, but not all of them are used. Instead, several keys can be used as needed within a unified key space, based on specific business requirements, to respectively carry different categories of thread-local storage content, such as startup and identity information, business operation context, temporary processing data, diagnostic monitoring information, and recovery control information. The purpose of setting multiple keys is to classify, organize, independently locate, and selectively access local data with different semantics.
[0027] Storage Unit: Each combination of task identifier and key identifier corresponds to a pointer-sized memory space, used to store a thread-local storage value. In this invention, the storage unit is the basic storage unit in a two-dimensional matrix.
[0028] pointer size ( ): The number of bytes occupied by the pointer on the target platform, which is 4 bytes on a 32-bit platform and 8 bytes on a 64-bit platform.
[0029] base address ( ): The starting memory address of the unified thread local storage area remains unchanged after being allocated once during the system startup phase.
[0030] Destructor: A callback function associated with a key, automatically invoked when a task exits or a key is released. It is used to release dynamic resources (such as heap memory, file handles, etc.) pointed to by thread-local storage values, preventing resource leaks. In this invention, the destructor is recorded in a key management table and invoked during task exit cleanup or key release cleanup.
[0031] Key Management Table ( ): Used to record the allocation status of each key ( This is a data structure containing flags and corresponding destructor pointers. During system initialization, the key management table is cleared, and all keys are initially unallocated. When the application calls... When assigning a new key, the system traverses the key management table to look it up. For slots with == 0, occupy the slot, record the destructor, and then return the key value (slot index).
[0032] Unified Thread Local Storage Area ( This is a contiguous memory region allocated once during system startup to store all TLS values for all tasks. Its size is... ,in The maximum number of tasks is preset. This represents the maximum number of keys.
[0033] The terms used above are only for explaining specific embodiments of the present invention and are not intended to limit the scope of protection of the present invention. Those skilled in the art will understand that other existing technologies with the same or similar functions can be employed without departing from the concept of the present invention.
[0034] Example 1: System Architecture like Figure 1As shown, this invention provides a cross-task accessible thread-local storage system. Its core lies in unifying the TLS data of all tasks into a two-dimensional local storage system composed of task and key dimensions. The system adopts a modular architecture, consisting of two core modules that work together to achieve a complete closed loop from storage area creation to cross-task access and cleanup / reclamation.
[0035] Specifically, the system includes the following functional modules: A unified storage module is used during the startup phase of the MMU-less embedded real-time operating system to allocate a contiguous memory region as a unified thread-local storage area based on the preset maximum number of tasks and keys. During system initialization, this module calculates the required memory size based on the maximum number of tasks and keys (e.g., 32 tasks × 32 keys = 4KB, or 16 tasks × 16 keys = 1KB, or 64 tasks × 16 keys = 1KB), allocates the contiguous memory all at once, and clears it to zero. No further dynamic memory allocation is performed during runtime. As a unified TLS storage area, taskID is used as the basis for row location and key is used as the basis for column location.
[0036] The unified thread-local storage area uses task identifiers as row indices and key identifiers as column indices. Each combination of task identifier and key identifier corresponds to a pointer-sized storage unit, which is used to store a thread-local storage value.
[0037] The address mapping module is used to locate the storage unit of the target task under a specified key identifier through linear address mapping based on the task identifier and key identifier of the target task, thereby enabling cross-task access to the thread-local storage value of any target task. The core of this module is to directly calculate the storage address based on the address calculation formula, without indirect access through a global pointer or switching to the target task context. When accessing data within the current task itself, the corresponding unit can be located based on the current task identifier and the specified key identifier; when accessing data from other tasks, the target unit can also be located directly based on the target task identifier and the specified key identifier without first switching to the target task context.
[0038] The two functional modules mentioned above work together to form a complete closed-loop system. Upon system startup, the unified storage module allocates a contiguous memory region as a unified... Storage area; During system operation, the address mapping module directly locates the storage unit based on the target task identifier and key identifier, enabling cross-task access. When a task exits or a key is released, the system performs cleanup and reclamation along the task dimension or key dimension. At the end of the runtime, there are two types of exit paths: one is by... Cleaning up the entire row, one type is by Processing entire columns ensures that the mechanism forms a closed loop from creation, access to exit and recycling.
[0039] All modules communicate with each other through well-defined APIs, ensuring the system's scalability and stability.
[0040] Example 2: General Process like Figure 2 As shown, this invention provides a method for implementing thread-local storage that is accessible across tasks, including stages such as mechanism establishment, key allocation, current task access, cross-task access, and task exit cleanup, specifically including the following steps: S1: Establishment of a unified storage area During the startup phase of the MMU-less embedded real-time operating system, the call is made. The interface, based on the preset maximum number of tasks and maximum number of keys Calculate the required storage space: Then, a contiguous block of memory is allocated at once as a unified thread-local storage area. , call Allocate memory, use ( ,0, Clear the memory region. Simultaneously, initialize the key information table. , each key The flag is set to 0.
[0041] The system is based on As a unified TLS store, As a basis for line positioning, This serves as the basis for column positioning. Thus, each... Each value corresponds to a storage unit in a two-dimensional matrix. Instead of creating keys piecemeal at a specific point in the task's execution, key spaces and unified storage areas are pre-established at the system level, enabling... It possesses a global organizational foundation from the outset that addresses all tasks and all keys.
[0042] S2: Key Management Table Creation and Key Assignment Create a key management table This table is used to record the allocation status of each key and its corresponding destructor. The key management table is initialized after the unified thread-local storage area is established; initially, all keys are marked as unallocated.
[0043] Application call The interface assigns a new key. The system performs the following operations: first, disable interrupt protection, then iterate through... Search The slot with ==0 is used to set the slot. =1 and record The destructor is then enabled, and interrupts are turned on. The returned key value (slot index) is used as the key identifier.
[0044] S3: Current task TLS access When the current task needs to access its own TLS data, it calls... or Interface. The system locates the storage unit using an address calculation formula based on the current task identifier and the specified key identifier, and then performs read or write operations.
[0045] S4: Cross-task access When a debug module, monitoring task, or management task needs to access the TLS data of another task, it calls... or interface.
[0046] The system performs the following operations: First, it performs parameter validation, checking whether the target task identifier is within the preset task identifier range, whether the specified key identifier is less than the maximum number of keys, and whether the key corresponding to the specified key identifier is in an assigned state in the key management table; then, it checks whether the target task exists and has not exited, calling OsTaskIsAlive(targetTaskID); finally, it calculates the storage address: Disable interrupt protection, read or write the value, then enable interrupts and return the operation result.
[0047] Cross-task access includes cross-task read operations and cross-task write operations. A cross-task read operation involves locating a storage unit using a linear address mapping based on the target task's task identifier and a specified key identifier, and then reading the thread-local storage value stored in that unit. A cross-task write operation involves locating a storage unit using a linear address mapping based on the target task's task identifier and a specified key identifier, and then writing the thread-local storage value to be written into that storage unit.
[0048] Cross-task read operations no longer depend on "who is currently running," but directly on "who the target task is and what the target key is." Therefore, debugging, monitoring, or management tasks in the system can directly read the target task's corresponding data without switching to the target task's context. On-site information. This makes... The traditional "thread-private and invisible data" has been transformed into "data units with clearly defined ownership relationships, but which are observable by the system in a directional manner".
[0049] The value of cross-task modification lies not in providing indiscriminate arbitrary write capabilities, but in providing a controlled local state adjustment mechanism for specific target tasks, specific key categories, and specific processing scenarios, thereby improving the system's task coordination capabilities, runtime management capabilities, and anomaly recovery capabilities.
[0050] S5: Task Exit Cleanup When the target task exits, call Interface. The system performs the following operations: ,like Skip it; otherwise ;like Skip this step; first read and save the original value. Then clear the storage unit. Then call the destructor. Release the saved original value.
[0051] When the target task exits, what needs to be addressed is not a scattered variable, but rather the entire task's process throughout the entire process. This corresponds to a single row of data in a two-dimensional matrix. This ensures that all data related to the task is included. Content is released uniformly at the end of its lifecycle, and there will be no omissions due to key scattering or data scattering.
[0052] S6: Key Release Cleanup When a key is released (e.g., when an application calls...) The system iterates through the entire column of memory cells corresponding to the key in the unified thread's local memory area. For each memory cell encountered, it first reads and saves the original value, then clears the memory cell to zero, and finally calls the destructor corresponding to the key to release the saved original value. After processing, the key is added to the key management table. The flag is reset to zero.
[0053] In this plan, It is not a single-task private concept, but a unified concept across the entire system. Category identifier. Therefore, when a key is no longer used, it is necessary to process the entire column of data for that key across all tasks, rather than processing a single point of content within a single task.
[0054] Example 3: Memory Layout and Address Calculation like Figure 3 As shown, the unified thread local storage area adopts a two-dimensional matrix memory layout. Let the maximum number of tasks be... The maximum number of keys is The total size of the storage area is .
[0055] Each task corresponds to a row in the matrix, and each key corresponds to a column in the matrix. Each storage unit consists of... The unique and definitive formula for calculating its storage address is: Storage address = base address + (target task identifier × maximum number of keys + key identifier) × pointer size; Expressed as a formula: ; ; in, To unify the base address of the thread-local storage area, This is the offset. The task identifier for the target task. This represents the maximum number of keys. To specify the key identifier, The pointer size on the target platform (4 bytes for 32-bit platforms and 8 bytes for 64-bit platforms).
[0056] Taking a 32-task x 32-key configuration as an example, assuming , To locate the storage unit of task 5 under key 3, then A .
[0057] Furthermore, let's take the storage unit under key 2 for locating task 5 as an example for verification: Storage address = g_tlsValues + (5 × 32 + 2) × 4 =g_tlsValues+162×4 =g_tlsValues+0x288.
[0058] This verification example demonstrates that, using the address calculation formula described above, the system can directly calculate the storage unit address of any target task under any key identifier in constant time, without traversal or hash lookup.
[0059] This address calculation formula achieves direct addressing with O(1) time complexity, requiring no pointer jumps and supporting direct location for any task. Traditional Accessing a database requires first obtaining the TLS table pointer of the current task, then performing a key lookup, necessitating at least two indirect addressing steps. This invention achieves single direct addressing through linear address calculation, eliminating pointer jump overhead.
[0060] Example 4: Cleanup Mechanism like Figure 4 As shown, the cleanup mechanism of this invention includes two paths: task exit cleanup and key release cleanup.
[0061] Task Exit Cleanup Path: When a target task exits, the system iterates through the corresponding row of storage units in the unified thread local storage area based on the target task's task identifier. For each storage unit, the original value is first read and saved, then the storage unit is zeroed out (to prevent re-entry in the destructor), and finally the destructor corresponding to the column containing that storage unit is called to release the saved original value. After processing, the entire row of data corresponding to the task is completely released. Key Release Cleanup Path: When a key is released, the system iterates through the entire column of storage units corresponding to that key in the unified thread local storage area. For each storage unit, the original value is first read and saved, then the storage unit is zeroed out, and finally the destructor corresponding to that key is called to release the saved original value. After processing, the entire column of data corresponding to that key is completely released, and the key is also removed from the key management table. The flag is reset to zero.
[0062] This cleanup mechanism ensures Resources are uniformly reclaimed upon task exit or key release, preventing omissions due to key or data scattering. The order of zeroing before calling the destructor effectively prevents recursion or reentrancy issues that might occur if the current TLS value is accessed again within the destructor.
[0063] Example 5: Typical Application Scenarios Scenario 1: Parent task pre-configures TLS context for child task Before the child task actually enters the running state, the parent task first determines the child task's... Then, according to the target key, write the initialization parameters, session identifier, context pointer, and other data into the corresponding subtask. This allows subtasks to directly use their pre-prepared local contexts upon startup, without needing to obtain them through global variables or complex parameter forwarding chains.
[0064] Scenario 2: Debugging task reads fault task on site When the target task encounters an anomaly, but its When the site remains in a unified storage area, debugging tasks can be performed according to the fault tasks. and target Directly read related Content. In this way, the debugging logic can extract fault information without intruding on the original execution flow of the target task or requiring the target task to actively cooperate.
[0065] Scenario 3: Monitoring task reads target task status snapshot Monitoring tasks can be performed periodically according to the target. Read the target task on certain diagnostic keys Data is used to create a snapshot of the task's state. This approach is simpler than directly intruding into the target task's internal processes and better preserves task boundaries than exposing internal state through globally shared variables.
[0066] Scenario 4: Reconstructing the local state of the target task using recovery logic In anomaly recovery scenarios, the recovery logic can first extract the necessary recovery information from the original TLS unit of the failed task, and then rewrite the recovery value into the corresponding unit of the reconstructed target task. In this way, TLS is no longer just a runtime temporary variable container, but also becomes the carrier of task-level local state in the anomaly recovery chain.
[0067] Example 6: Specific Implementation Example by Taking an embedded RTOS architecture as an example, the system defaults to a maximum of 32 tasks, a maximum of 32 keys, and a pointer size of 4 bytes. The system calls [the following function] during startup. The interface calculates a memory size of 32 × 32 × 4 = 4096 bytes (4KB), allocating a contiguous memory region in one go. .
[0068] The application first calls Assign a diagnostic information key to obtain Then create three tasks: Monitoring tasks Business task A Business task B.
[0069] Business task A crashed unexpectedly during execution. (Monitoring task) Call Read the diagnostic information for business task A. System calculation storage address: It directly locates the storage unit of business task A under key 0, reads the TLS value stored therein, and obtains the on-site information before the crash for problem localization.
[0070] When business task B exits normally, the system calls... Interface, traversal Step 31 reads and releases the TLS values of business task B under each key in sequence, calls the corresponding destructor to release dynamic resources, and finally clears the storage unit.
[0071] One or more embodiments in this application are intended to cover all such substitutions, modifications, and variations that fall within the broad scope of this application. Therefore, any omissions, modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of one or more embodiments in this application should be included within the protection scope of this application.
[0072] If flowcharts are used in this application, they are used to illustrate the operations performed by the system according to embodiments of this application. It should be understood that the preceding or following operations are not necessarily performed in exact order. Instead, the steps can be processed in reverse order or simultaneously. Furthermore, other operations can be added to these flows, or one or more steps can be removed from these flows.
[0073] The foregoing has provided a detailed description of a method and system for implementing cross-task accessible thread-local storage, as provided in this application. The above description of the disclosed embodiments enables those skilled in the art to implement or use this application. Various modifications to these embodiments will be readily apparent to those skilled in the art, and the general principles defined herein may be implemented in other embodiments without departing from the spirit or scope of this application. Therefore, this application is not to be limited to the embodiments shown herein, but is to be accorded the widest scope consistent with the principles and novel features disclosed herein.
Claims
1. A method for implementing cross-task accessible thread-local storage, based on an MMU-less embedded real-time operating system, characterized in that... Includes the following steps: During the startup phase of the MMU-free embedded real-time operating system, a contiguous memory region is allocated once as a unified thread-local storage area based on the preset maximum number of tasks and the maximum number of keys. The unified thread-local storage area uses task identifiers as row indices and key identifiers as column indices. Each combination of task identifiers and key identifiers corresponds to a pointer-sized storage unit, which is used to store a thread-local storage value. Based on the task identifier and the key identifier of the target task, the storage unit of the target task under the specified key identifier is located by linear address mapping, so as to realize cross-task access to the thread-local storage value of any target task; The linear address mapping method is specifically as follows: The offset is calculated according to a preset formula based on the task identifier of the target task, the maximum number of keys, and the specified key identifier. Obtain the base address of the unified thread local storage area; The sum of the base address and the offset is used as the storage address of the storage unit; The preset formula is specifically as follows: ; in, The offset is... The task identifier for the target task. The maximum number of keys, For the specified key identifier, This is the pointer size.
2. The method for implementing cross-task accessible thread-local storage according to claim 1, characterized in that, After the unified thread local storage area is established and before the cross-task access, the following steps are also included: Establish a key management table, which is used to record the allocation status of each key; The key management table is initialized after the unified thread local storage area is established, and initially all keys are marked as unallocated. When a new key needs to be assigned, the key management table is traversed to find the key in the unassigned state, the found key is marked as assigned, and the key identifier corresponding to the key is returned.
3. The method for implementing cross-task accessible thread-local storage according to claim 2, characterized in that, The key management table is also used to record a destructor function corresponding to each key, and the destructor function is used to release the dynamic resources pointed to by the thread-local storage value; When assigning the new key, the destructor is also registered for the new key; Each key corresponds to a column in the unified thread local storage area, and each task identifier corresponds to a row in the unified thread local storage area.
4. The method for implementing cross-task accessible thread-local storage according to claim 3, characterized in that, It also includes the following steps: When the target task exits, the corresponding entire row of storage units in the unified thread local storage area is traversed according to the task identifier of the target task. For each of the storage cells encountered, first read and save the original value in the storage cell, then clear the storage cell to zero, and then call the destructor function corresponding to the column where the storage cell is located to release the saved original value.
5. The method for implementing cross-task accessible thread-local storage according to claim 4, characterized in that, It also includes the following steps: When any of the keys is released, traverse the entire column of storage units corresponding to any of the keys in the unified thread local storage area; For each of the storage cells encountered, first read and save the original value in the storage cell, then clear the storage cell to zero, and then call the destructor function corresponding to the column where the storage cell is located to release the saved original value.
6. The method for implementing cross-task accessible thread-local storage according to claim 2, characterized in that, Before performing the cross-task access, the following steps are also included: Verify whether the task identifier of the target task is within the preset task identifier range; Verify whether the specified key identifier is less than the maximum number of keys; Verify whether the key corresponding to the specified key identifier is in an assigned state in the key management table; If any check fails, the cross-task access will be terminated.
7. The method for implementing cross-task accessible thread-local storage according to claim 1, characterized in that, The cross-task access includes the following forms: Cross-task read operations and cross-task write operations; The cross-task read operation is as follows: based on the task identifier and the specified key identifier of the target task, the storage unit is located through the linear address mapping method, and the thread-local storage value stored in the storage unit is read. The cross-task write operation is as follows: based on the task identifier and the specified key identifier of the target task, the storage unit is located through the linear address mapping method, and the thread-local storage value to be written is written to the storage unit.
8. A cross-task accessible thread-local memory system, implemented based on an MMU-less embedded real-time operating system, characterized in that, include: A unified storage module is used to allocate a contiguous memory region as a unified thread-local storage area once during the startup phase of the MMU-less embedded real-time operating system, based on a preset maximum number of tasks and a maximum number of keys. The unified thread-local storage area uses task identifiers as row indices and key identifiers as column indices. Each combination of task identifiers and key identifiers corresponds to a pointer-sized storage unit, which is used to store a thread-local storage value. The address mapping module is used to locate the storage unit of the target task under the specified key identifier through linear address mapping based on the task identifier and the key identifier of the target task, so as to realize cross-task access to the thread-local storage value of any target task. The linear address mapping method is specifically as follows: The offset is calculated according to a preset formula based on the task identifier of the target task, the maximum number of keys, and the specified key identifier. Obtain the base address of the unified thread local storage area; The sum of the base address and the offset is used as the storage address of the storage unit; The preset formula is specifically as follows: ; in, The offset is... The task identifier for the target task. The maximum number of keys, For the specified key identifier, This is the pointer size.
Citation Information
Patent Citations
Method and device for realizing thread local storage
CN106445656A
Multi-thread memory management method and system fusing large page and thread local distribution area
CN121705032A
TLS storage model compatible method oriented to heterogeneous closed source drive fusion operation
CN122240362A