信号量
![[Pasted image 20250518115216.png]]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| SemaphoreHandle_t xSemaphoreCreateBinary(void);
SemaphoreHandle_t xSemaphoreCreateCounting( UBseType_t uxMaxCount, UBseType_t uxInitialCount );
xSemaphoreTake( SemaphoreHandle_t xSemaphore, TickType_t xTicksTowait );
xSemaphoreGive(SemaphoreHandle_t xSemaphore);
xSemaphoreDelete(SemaphoreHandle_t xSemaphore);
|
实例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "esp_log.h"
SemaphoreHandle_t bin_sem;
void taskA(void* param) { while (1) { xSemaphoreGive(bin_sem);
vTaskDelay(pdMS_TO_TICKS(1000)); } }
void taskB(void *param) { while (1) { if(pdTRUE == xSemaphoreTake(bin_sem, portMAX_DELAY)) { ESP_LOGI("bin", "task B take binsem success"); } } }
void app_main(void) { bin_sem = xSemaphoreCreateBinary();
xTaskCreatePinnedToCore(taskA, "taskA", 2048, NULL, 3, NULL, 1);
xTaskCreatePinnedToCore(taskB, "taskB", 2048, NULL, 4, NULL, 1); }
|
互斥锁
![[Pasted image 20250518105647.png]]
优先级:A>B>C,
任务C与任务A优先级翻转,先C后B
实例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "esp_log.h" #include "driver/gpio.h" #include "dht11.h"
SemaphoreHandle_t dht11_mutex;
void taskA(void* param) { int temp, humidity; while (1) { xSemaphoreTake(dht11_mutex, portMAX_DELAY); vTaskDelay(pdMS_TO_TICKS(500)); if (DHT11_StartGet(&temp, &humidity)) { ESP_LOGI("dht11", "taskA-->temp:%d, humidity:%d%%", temp / 10, humidity); } xSemaphoreGive(dht11_mutex); vTaskDelay(pdMS_TO_TICKS(1000)); } }
void taskB(void *param) { int temp, humidity; while (1) { xSemaphoreTake(dht11_mutex, portMAX_DELAY); vTaskDelay(pdMS_TO_TICKS(500)); if (DHT11_StartGet(&temp, &humidity)) { ESP_LOGI("dht11", "taskB-->temp:%d, humidity:%d%%", temp / 10, humidity); } xSemaphoreGive(dht11_mutex); vTaskDelay(pdMS_TO_TICKS(1000)); } }
void app_main(void) { dht11_mutex = xSemaphoreCreateBinary();
xSemaphoreGive(dht11_mutex);
xTaskCreatePinnedToCore(taskA, "taskA", 2048, NULL, 3, NULL, 1);
xTaskCreatePinnedToCore(taskB, "taskB", 2048, NULL, 3, NULL, 1); }
|