In the two types of RTOS, threads are stored as priority queues, and some may support threads with the same priority. In this case, each thread with the same priority is stored as a circular linked list. This priority queue is stored as an array. As shown in:
During kernel scheduling, you need to find the thread with the highest priority from the ready queue. At first glance, you can find the maximum number of algorithms in the array. Furthermore, the range of numbers is known in advance. The problem is described as follows:
- A fixed-length array, such as an array of 32 numbers.
- Each location represents a priority, that is, a number.
- Each priority can be null, that is, no threads are at this priority, and no operations are involved.
- Find the smallest priority (that is, the highest priority) on the priority that is not null ).
There are two ways to solve this problem.
- The traditional method is used to traverse the ready queue to find the minimum value, but the time is uncertain and the time complexity is O (n ).
- Use the space-based time change method. In the embedded OS, the number of threads is not very large, usually less than 256, so all the cases can be listed in advance. For example, if the system has a maximum of 8 threads and there are two or three threads, the value is 0b00000110. In this case, the highest priority is 2. The binary format also saves space.
From the second approach above, if there are eight priorities, we should prepare a priority table in advance:
?
01. Const unsigned char bitmap [] =
02 .{
03./* 00 */0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
04./* 10 */4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
05./* 20 */5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
06./* 30 */4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
07./* 40 */6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
08./* 50 */4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
09./* 60 */5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
10./* 70 */4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
11./* 80 */7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
12./* 90 */4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
13./* a0 */5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
14./* B0 */4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
15./* C0 */6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
16./* D0 */4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
17./* E0 */5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
18./* f0 */4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
19 .};
?
In this way, the highest priority can be found in the O (1) time under any thread combination.
?
Of course, there is another problem. Under 8 priorities, the table volume is tolerable, but under 32,256, the table volume is too large. The solution is, for example, 32 priorities, 32 is considered as 4 bytes. For each byte, the above 8 priority table is used to find the maximum value of each byte, and then merge the values, find the highest priority.
Scheduling Algorithm for bitmap in RTOs