当前位置:网站首页>Bit band operation of semaphore protection
Bit band operation of semaphore protection
2022-07-27 17:16:00 【Embedded Linux,】
Hello everyone , The problem of interrupting operation variables written in the last article , The Osprey helped reply , You can look at this article again .

CM3 Bit band operation
If the memory system supports “ Lock transmission ”( lockedtransfers), Or there is only one host on the bus , You can also use CM3 To realize the operation of mutual exclusion lock . By using bit bands , Can be in C Implement mutual exclusion in the program , But the operation process is different from mutually exclusive access . When using bit to do the control mechanism of resource allocation , You need to use a memory unit with a bit storage area ( such as , One word ), Each bit of the memory unit indicates that the resource is being used by a specific task . The reading and writing of the bit aliased area is essentially locked “ read ‐ Change ‐ Write ”( During transmission, the bus cannot be occupied by other hosts ). therefore , As long as each task modifies only the lock positions assigned to them , The value of other task lock positioning will not be lost , Even if two tasks write their own lock bits at the same time, they are not afraid , Pictured :
Take two tasks as examples , As follows :( The red arrow represents jump execution )

Mission 2 First read and judge , Then jump to the task for some reason 1 Perform read 、 Judge 、 Set operation , And for some reason, after setting, it jumps to the task 2 To set up 、 Read operation , Then came the task 1 To perform read and judge operations , Found another location 1, Then abandon the resource , Then when running the task 2 when , Because it's still the previous data , So the final judgment is that other tasks are occupied , Also give up the resource . The end result is that both tasks give up the resource . But it's rare , Because this needs to jump back and forth in several instructions to happen , Generally, the whole operation process will only be interrupted by other tasks once .
Then analyze the following execution process , Mission 1 After reading, the task 2 Occupation flag is set , Then return to the task 1 Judge , The result is the task 1 Occupancy resources , Even if the subsequent tasks 2 It's broken , Mission 2 It will also read the task 1 Occupation sign of , Thus giving up resources .

The following is the interrupt judgment operation ( Judgment not executed ) Where you may jump later , Self analysis ( The key is setting ).

So what does bit aliasing avoid ? It is actually used to avoid reading - Change - Because of interruption in the operation of writing , The data set by other tasks is lost due to the last writing step . as follows :

Because there is an interrupt when setting , Lead to task 2 Set up , But because what is interrupted is the setting operation , So when you go back to settings , The read data is still the previous data , Setting operation at this time will inevitably lead to tasks 2 The setting operation of is lost , And eventually lead to serious consequences .
After further thinking, it is found that the key to these operations is to determine whether you really own the resource after setting the flag . Is it possible to set this flag without the previous read judgment operation ? I think it's ok , However, there is a disadvantage here because you can set other task setting flags by yourself no matter whether you have other task setting flags , Once the flag is set in the case of other task settings , You have to clear your own logo , Add the operation you set before , It is obviously less efficient than setting after judgment .
Does it mean that there is no mutually exclusive access without bit band operation ? Of course not. , The simple way is to turn off the interrupt , But the previous analysis found , In fact, the key point is not to destroy other signs , In this way, we can treat bytes as bits , You set your byte flag , I set my byte flag , Mutual interference , It can also achieve the effect of bit band operation , It just takes up more space . But the biggest reading type of MCU is double Type data , stay stm32 Middle is 8 byte , That is, the maximum number of tasks that can be set is 8 A mission , And the bit takes the action 8*8=64 A mission , But can we use multiple judgments to increase the number of tasks ? For example, two. double When combined, use the method of judging two variables twice to determine whether to occupy resources . This is a solution , But is there any risk in this method ? Through the following analysis, we can actually get the answer .
After further thinking , You'll find out , The most important thing is the setting “ Read ” This confirmation operation , This operation is the watershed of the whole resource locking operation . In the whole operation process , No matter which operation is interrupted , Then set the flag bit by other tasks , The key is to read this step , No other task sets the flag bit when who reads the variable into the register , Whoever takes up resources .
On the macro level, the two tasks can be considered to be performed at the same time , But when reading , If the two tasks are carried out at the same time , There must be a sequence ( No matter who comes first and who comes later ,, As long as the other party doesn't give up the occupation before you read , Will give up occupation , And if there is simultaneous reading ( Two cpu) The situation of , Then it must be the result of giving up resources at the same time ). Now that the read operation has been performed , Then the setting operation must be carried out , That is to say, two people set the flag bit at the same time , Are ready to occupy resources , No matter who reads , The end result is that resources have been occupied , Then I gave up , Even if the task is interrupted immediately after reading , But it will not affect the subsequent judgment of the task 、 Give up the operation , Because the data you read has determined all the subsequent operations of the task , So the key operation is read operation , What data are you reading .
Then the worst case is as mentioned above , Both tasks are found to be occupied by other tasks after reading , Then give up resources , Then we analyze other possibilities , Theoretically, there are four possibilities for reading data for two tasks ,11,10,01,00. But actually 00 It can be excluded , Because it must have been set before reading , Well, except
In addition to the flag bits of the task itself, there are only flag bits that other tasks may set , That is, either set , Or it's not set . If set , There are two situations , If another task has given up occupying , Then it can occupy resources , If the task does not give up resources before reading , Then give up resources .
It may be clearer to use a diagram :

In fact, after in-depth analysis, we can find , These are the two key operations mentioned before, and their sequence , The key operation to decide whether to occupy resources is read operation . Whoever reads that no other task is occupied first will occupy the resource .
Now let's consider whether it is possible for two tasks to find that neither of them requests to occupy resources at the same time after reading ? We know that mutually exclusive operation is an operation process specially set to avoid this situation , If this situation cannot be avoided, no amount of analysis is useless . In fact, this situation is impossible , Because a task has set the flag bit of this task when reading , Once read, another task does not set the flag bit , Even if it takes up resources , Then another task must be occupied by the task when reading , Will give up occupation , There will be no such task that is not occupied by the task when reading , Another task doesn't occupy it when reading , Because only one task can read at a time , It can't be at the same time , Even when reading at the same time , The final result is to give up resources at the same time . That is to say, after the setting operation, the task is given two possibilities , Occupy or not occupy , At the same time, it also avoids the situation that two tasks are occupied at the same time .
So the answer to the previous question is that there is no risk , Because the worst case is that two tasks give up resources at the same time .
In a word , Who reads without other tasks , No matter what happens later , I have this resource .
---------------------------------------------------------------------------------------2018-08-18Osprey
In the thinking of the above mutex problem , We can come to a conclusion , What data you read determines your next action , And according to the previous discussion, it can be found that even if the total interruption is not turned off, it will not lead to the confusion of resource use , Based on this consideration , I think that in many cases, the interrupt can not be closed , But when I see the following uCOS II Source code time , I think it's OK not to close the interrupt , But after deep thinking, it is found that the interrupt must be turned off .

See the above message mailbox OSMboxPend Source code , It can be found that the interrupt is closed when reading the message pointer , But according to the previous thinking , Even if there is no shutdown interrupt , It's a big deal to be interrupted during reading , And then OSEventPtr Set to non-zero state . But it will not affect the later judgment operation , But is it true ?

From the analysis of the above two situations, we can find , It can ensure the correct execution of the judgment statement without closing the interrupt ( It is assumed that pmsg = pevent->OSEventPtr; This article C Language statements need 3 Assembly statement operation execution ), But finally, according to the reading pmsg The result of value interpretation will lead to two distinct effects . One is to return directly , The current task is executed normally , Another case is to set the current task to wait , In addition, there may be operations that may affect the chaos of the whole system , This is absolutely not allowed .
When analyzing the mutex of shared resources before, we found that this situation also occurs , But why can't it be all right ? This is because the worst case is that you can't get shared resources , Generally speaking, resources are not available, although rare , But in the case of interrupting the operation before, it does happen , However, even if resources are not available, it will not lead to serious consequences of the system , Because generally speaking , When you don't get resources , Next time, I will continue to try to get , The same is true for another task , Regardless of the interruption , It just leads to the re acquisition of resources , This is an acceptable situation . But now the analysis of this situation does not allow , Because it could work normally , You put it into a waiting state , It is likely to lead to serious consequences . So when it comes to judgment , If you interrupt the different results of judgment, it will lead to very serious consequences , Then it is better to read 、 Judge 、 The classification action is set to atomic operation ( Uninterrupted operation ), The general way to set the whole process to atomic operation is to turn off interrupt .
-------- to update 2018/08/23 Osprey


边栏推荐
- Character stream read file
- VS2019 C语言如何同时运行多个项目,如何在一个项目中添加多个包含main函数的源文件并分别调试运行
- C语言之函数
- UITableView 基本使用和优化
- day07 作业
- Servlet uses cookies to realize the last login time of users
- This large model sparse training method with high accuracy and low resource consumption has been found by Alibaba cloud scientists! Has been included in IJCAI
- Storage of data in C language
- Kubernetes Part 7: using kubernetes to deploy prometheus+grafana monitoring system (kubernetes work practice class)
- 高精度定时器
猜你喜欢

KMP模板——字符串匹配

Data collection: skillfully using Bloom filter to extract data summary

立创EDA——原理图的布局与检查(三)

Natural sorting: comparable interface, customized sorting: the difference between comparator interface

Swift QQ authorized login pit set

webView基本使用

C语言之结构体及位段

苹果官网罕见打折,iPhone13全系优惠600元;国际象棋机器人弄伤对弈儿童手指;国内Go语言爱好者发起新编程语言|极客头条...

SAP UI5 FileUploader 使用的隐藏 iframe 和 form 元素的设计明细

JD Zhang Zheng: practice and exploration of content understanding in advertising scenes
随机推荐
C语言之指针进阶
App crash collection and analysis
腾讯云上传使用
Gartner authority predicts eight development trends of network security in the next four years
Natural sorting: comparable interface, customized sorting: the difference between comparator interface
2021-06-18 SSM项目中自动装配错误
Three table joint query 3
Hyperlink parsing in MD: parsing `this$ Set() `, ` $` should be preceded by a space or escape character`\`
The chess robot broke the finger of a 7-year-old boy. Netizen: it violated the first law of robots
node包依赖下载管理
国产新冠口服药为什么是治艾滋病的药
关于 SAP UI5 应用 ui5.yaml 里的 paths 映射问题
UITableView 基本使用和优化
Technical practice dry goods | from workflow to workflow
下棋机器人折断7岁男孩手指,网友:违反了机器人第一定律
渐变环形进度条
JSP El expression, JSTL tag
Measured: the performance of cloud RDS MySQL is 1.6 times that of self built
About paths mapping in SAP ui5 application ui5.yaml
2021-06-18 automatic assembly error in SSM project