当前位置:网站首页>[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 :

边栏推荐
- 【数字信号】基于matlab模拟窗函数频谱细化【含Matlab源码 1906期】
- Wechat applet picture verification code display
- Docker Deployment redis
- 混沌工程,了解一下
- Three Solution to the problem of inaccuracy in radiographic testing under the condition of non full screen canvas of JS
- Batch renaming of images by MATLAB
- What is the same origin policy?
- [things about gbase] gbase 8s high availability technology and case analysis (issue 02)
- All 32 keyword classifications of C language C89 (C90)
- What is the difference between concurrency and parallelism?
猜你喜欢

Dot and cross product

Test - use case - detail frenzy

《德阳市餐饮服务业油烟污染防治管理办法(征求意见稿)》之创新油烟监管

fatal: The upstream branch of your current branch does not match the name of your current branch.

Return, const, volatile keywords

Taylor formula and common expansion

Revit API:明细表 ViewSchedule

开口式霍尔电流传感器助力直流配电改造

点乘和叉乘

2. camera calibration
随机推荐
Design of message push platform
docker 部署redis
All 32 keyword classifications of C language C89 (C90)
Cloud native architecture (05) - Application Architecture Evolution
Docker Deployment redis
Three Solution to the problem of inaccuracy in radiographic testing under the condition of non full screen canvas of JS
== 和 equals 的区别是什么?
Confused test / development programmers, different people have different stories and different puzzles
Facebook open source shimmer effect
Visual explanation of clockwise inner curve in Green's formula hole digging method
Generative countermeasure networks (Gans) and variants
Docker deploy redis
MySQL architecture (basic)
Quantitative investment model -- research interpretation of high frequency trading market making model (Avellaneda & Stoikov's) & code resources
Perfectionist win10 installation guide
Generate all possible binary search trees
What are the good solutions for industrial control safety of production line
First week of summer vacation
Application of acrel-3000web power management system in Duba Expressway
Test - use case - detail frenzy