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

边栏推荐
- [interview experience package] summary of experience of being hanged during interview (I)
- Different objects use the same material and have different performances
- 工作中一些常用的工具函數
- Tupu software intelligent wind power: operation and maintenance of digital twin 3D wind turbine intelligent equipment
- 数据库中索引原理及填充因子
- NLP工程师是干什么的?工作内容是什么?
- return、const、volatile关键字
- 【面试经验包】面试被吊打经验总结(一)
- 被同事坑到周末加班, 没见过把Redis用成这个鬼样子的。。。
- Cloud native architecture (05) - Application Architecture Evolution
猜你喜欢

Synthetic big watermelon games wechat applet source code / wechat game applet source code

抖音实战~手机号密码一键注册登录流程(限制手机终端登录)

点乘和叉乘

Tupu software intelligent wind power: operation and maintenance of digital twin 3D wind turbine intelligent equipment

Idea automatically generates unit tests, doubling efficiency!

Recommend 4 flutter heavy open source projects

AI技术在医学领域有什么用?

医疗是什么?AI医疗概念解析AI

1. < tag dynamic programming and path combination problem > lt.62 Different paths + lt.63 Different paths II

云原生架构(05)-应用架构演进
随机推荐
2021-11-23: Regulations: l[1] corresponds to a, l[2] corresponds to B, l[3] corresponds to C
What is the difference between concurrency and parallelism?
Digital property management has become a trend. How can traditional property companies achieve digital butterfly change through transformation?
docker 部署redis
Digital supply chain management system for metallurgical industry: platform lean enterprise management to help the high-quality development of the industry
【Bug】C# IQueryable里的元素更改不了值
抖音实战~手机号密码一键注册登录流程(限制手机终端登录)
Nice input edit box
Use of reverse tools IDA and GDB
Return, const, volatile keywords
== 和 equals 的区别是什么?
fatal: The upstream branch of your current branch does not match the name of your current branch.
Expander+listbox of WPF effect
2018/gan:self attention generating adversarial networks
Tupu software intelligent wind power: operation and maintenance of digital twin 3D wind turbine intelligent equipment
Keywords such as extern and struct
如何利用數倉創建時序錶
Solve the problem of project dependency red reporting
解决项目依赖报红问题
合成大西瓜小游戏微信小程序源码/微信游戏小程序源码