当前位置:网站首页>[FreeRTOS] 07 binary semaphore and count semaphore
[FreeRTOS] 07 binary semaphore and count semaphore
2022-06-24 00:02:00 【xiaobaibai_ two thousand and twenty-one】
This section begins with freeRTOS The amount of signal , Let's start with the most basic binary semaphore , Counting semaphores will be explained later , Finally, the difference between semaphore and critical section protection .
1) What is semaphore
Semaphore is a method used to solve resource sharing and process synchronization in operating system .
Give two examples to illustrate .
Resource sharing : Suppose we have a serial port in our system , Each task sends data through it , This serial port can be regarded as a shared resource ; If you let the task access the serial port at will without control , It is likely that a task will send part of the data , Serial port resources are preempted by other tasks , New data sent ; This causes a shared resource error . We hope that when a task accesses the serial port , Other tasks that need to access the serial port are waiting , Until the task of occupying the serial port is used up, and the serial port resources are released , Then it's the next task to visit .
Semaphores are used to deal with such problems , We can make an agreement , Before accessing serial port resources , Each task competes to obtain semaphore first , The task that obtains the semaphore can access the serial port , Other tasks are ( Semaphore ) Blocking ; Wait until the first task is visited , It releases semaphores , Let the blocked tasks compete again , It's the same after that , The task of obtaining the semaphore can obtain the right to use the serial port . In this way, we can solve the problem of resource sharing through semaphores .
Synchronization tasks : Semaphores are simple for task synchronization , If there is a sequence requirement between multiple tasks , Required tasks A Completed the event a, To perform a task B The function in b, So we can be in the event a Then release a semaphore , And in the b Wait for this semaphore before executing , Then the task is guaranteed A、B Events in are executed synchronously .
Semaphores act a bit like global identifiers , We can also use global variables to share resources and synchronize tasks , Only the semaphore also has the function of blocking tasks , It is more convenient to use in the operating system .
2) Binary semaphore
Binary semaphore just as the name suggests , It has only two states , Being occupied can be seen as 0 state , Being unoccupied can be regarded as 1 state .
freeRTOS Provided binary semaphore , It is mainly operated by the following functions :
Create a binary semaphore :
SemaphoreHandle_t xSemaphoreCreateBinary(void); // Create a binary semaphore
SemaphoreHandle_t xSemaphoreCreateBinaryStatic( StaticSemaphore_t *pxSemaphoreBuffer ); // Create binary semaphores statically , You need to specify the address space of the semaphore
Release semaphore :
BaseType_t xSemaphoreGive( SemaphoreHandle_t xSemaphore ); // Release semaphore
BaseType_t xSemaphoreGiveFromISR( SemaphoreHandle_t xSemaphore, signed BaseType_t *pxHigherPriorityTaskWoken); // Release semaphores from interrupts , The return value of the latter parameter indicates whether a high priority task is ready , If there is , You need to switch tasks
Acquisition semaphore :
BaseType_t xSemaphoreTake( SemaphoreHandle_t xSemaphore, TickType_t xTicksToWait ); // Acquisition semaphore , The latter parameter is the blocking timeout
BaseType_t xSemaphoreTakeFromISR(SemaphoreHandle_t xSemaphore, BaseType_t *pxHigherPriorityTaskWoken); // Get semaphore in interrupt
We use an example to illustrate how to use binary semaphores :
Task02 Used to create semaphores , And every 1s Send a semaphore

Task03 Wait for the semaphore , Once you get , Then print the prompt :

The running results of this example are as follows , It can be found from the time stamp printed ,Task02 Once the semaphore is sent ,Task03 A printout is made immediately , Same as the expected operation results :

If you want to send a semaphore in an interrupt , You can write the code as follows :

The two selected lines are the transmitted semaphores , And deal with situations where high priority tasks are ready .
3) Count the semaphore
freeRTOS Count semaphores provided in , It is different from binary semaphore , It can record the number of times the semaphore is sent , That is to say, the state of the semaphore can be more than 0 and 1, It can be a natural number , That is, it can indicate that the number of resources is greater than 1 The situation of .
such as , We have a memory space , share 10 Bytes , Then we can use an initial value of 10 Count semaphores to manage , Every space used , The semaphore is reduced 1; Every time you release a space , Semaphore plus 1; The semaphore is greater than 0, It means there is space available ; The semaphore is reduced to 0, It means there is no space available .
It can be said that binary semaphore is a special case of counting semaphore , Binary semaphore is the maximum count value 1 Count semaphore .
freeRTOS Count semaphore provided , It is mainly operated by the following functions :
Create a count semaphore :
SemaphoreHandle_t xSemaphoreCreateCounting(UBaseType_t uxMaxCount, UBaseType_t uxInitialCount ); // Create a count semaphore , The two parameters are : Maximum count 、 Initial value
SemaphoreHandle_t xSemaphoreCreateCountingStatic( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount, StaticSemaphore_t * pxSemaphoreBuffer );// Create count semaphores in static form , You need to specify the address space of the semaphore
Release semaphore 、 Get the function of semaphore , Same as binary semaphore , I won't repeat it here .
When using count semaphores , To change the following macro definition to 1:
#define configUSE_COUNTING_SEMAPHORES 1
We also use an example to illustrate how to use counting semaphores :
stay Task02 Count semaphores are defined in , And initialize to 5, After every 1s Send a semaphore :

Task03 Waiting for semaphores in the , And delay for a short time , For easy observation of printed information :

The code runs as follows :
You can see , stay Task02 The semaphore is created and initialized to 5 after ,Task03 Yes 5 Time ; After every 1 second Task02 Send a semaphore ,Task03 Do it once :

4) Relationship between semaphore and critical segment
In the use of semaphores to protect shared resources , We found that , Shared resources protected by semaphores , It is similar to the critical section mentioned in the previous section , The purpose is to protect a piece of code from accidental access .
The difference is , The protection of critical zone is more strict , Once it is protected , Other interrupts 、 No task will be performed , You cannot exit until the current task is completed ; The protection of semaphores is not so strict , It limits only those tasks that wait for this semaphore , Tasks or interrupts that are not related to this semaphore , It is unaffected .
Okay , That's all for this section . In the next section, we will continue to explain semaphores , Discuss a classical problem related to it —— Priority reversal .
If you find it useful, you can pay attention to the author's wechat “ Xiaobai learns Electronics ”, You can find the code and data download address in the official account :

边栏推荐
- Loop caused by add of sublist in list
- Different objects use the same material and have different performances
- 暑假第一周
- == 和 equals 的区别是什么?
- Total number of combinations ii[each element can only be solved by + once]
- matlab实现对图像批量重命名
- What is the same origin policy?
- Smart doc + Torna compatible version
- Save: software analysis, verification and test platform
- Kubernetes basic concept
猜你喜欢

Cvpr2019/ image translation: transgaga: geometry aware unsupervised image to image translation

What is the use of AI technology in the medical field?
![复原IP地址[标准回溯+标准剪枝]](/img/e6/5f9d2a5af973b6c7051ed434a4b93d.png)
复原IP地址[标准回溯+标准剪枝]

Web site SSL certificate
![The input parameter is object, but it was passed as [object object] because it needs to be converted to JSON format](/img/8c/b1535e03900d71b075f73f80030064.png)
The input parameter is object, but it was passed as [object object] because it needs to be converted to JSON format

What is medical treatment? AI medical concept analysis AI

How to ensure reliable power supply of Expressway

Save: software analysis, verification and test platform

量化投资模型——高频交易做市模型相关(Avellaneda & Stoikov’s)研究解读&代码资源

Learn PWN from CTF wiki - ret2text
随机推荐
Docker deploy redis
Use of reverse tools IDA and GDB
docker 部署redis
The group procurement management system of daily chemical supplies industry changes the traditional procurement mode and reduces the procurement cost
Application of acrel-3000web power management system in Duba Expressway
《德阳市餐饮服务业油烟污染防治管理办法(征求意见稿)》之创新油烟监管
Three cool and coquettish bottom navigation
【面试经验包】面试被吊打经验总结(一)
迷茫的测试/开发程序员,不同人有着不同的故事、有着不同的迷茫......
Six complete open source projects, learning enough at a time
合成大西瓜小游戏微信小程序源码/微信游戏小程序源码
UART协议时序总结
Generate all possible binary search trees
Chaos engineering, learn about it
Kubernetes basic concept
物联网卡设备接入EasyCVR,如何查看拉流IP以及拉流时间?
MySQL architecture (basic)
Batch renaming of images by MATLAB
Recommend 4 flutter heavy open source projects
EF Core中的三类事务(SaveChanges、DbContextTransaction、TransactionScope)