本文基于ESP32-S开发 之 FreeRTOS Task
本文的主线 信号量 => 简介 => 同步
信号量
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
| #include <stdint.h> #include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h>
sem_t sem;
void *testfunc(void *arg) { while(1) { sem_wait(&sem); printf("hello world...\n"); } }
int main() { pthread_t ps; sem_init(&sem, 0, 0); pthread_create(&ps, NULL, testfunc, NULL); while(1) { sem_post(&sem); sleep(5); } return 0; }
|
1 2 3 4 5 6 7
| gcc sem_demo.c -o sem_demo -lpthread
./sem_demo
|
简介
Binary semaphores are used for both mutual exclusion and synchronisation purposes.
同步
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
| #include <Arduino.h>
SemaphoreHandle_t xBinarySemaphore;
void vTaskTake(void *pvParameters); void vTaskGive(void *pvParameters);
void setup() { xBinarySemaphore = xSemaphoreCreateBinary();
xTaskCreate(&vTaskTake, "Task Take", 1024, NULL, 1, NULL); xTaskCreate(&vTaskGive, "Task Give", 1024, NULL, 1, NULL); }
void loop() { }
void vTaskTake(void *pvParameters) { for (;;) { xSemaphoreTake(xBinarySemaphore, portMAX_DELAY); printf("Take Semaphore\r\n"); } }
void vTaskGive(void *pvParameters) { for (;;) { vTaskDelay(5000); printf("Give Semaphore\r\n"); xSemaphoreGive(xBinarySemaphore); } }
|
参考