我正在使用FREERTOS并尝试实现互斥。我想知道如何重写它,所以我不需要GOTO(因为这是一种不好的做法),或者这是美国的有效GOTO案例。谢谢
void mainThread(void const * argument) {
uint8_t buff[100];
writeMutex = xSemaphoreCreateMutex();
if (writeMutex != NULL) {
osThreadDef(compassReadThread, compassReadThread, osPriorityNormal, 0, 128);
compassReadTaskHandle = osThreadCreate(osThread(compassReadThread), NULL);
} else {
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, 1);
}
for (uint16_t i = 0; i < 50; i++) {
if (xSemaphoreTake(writeMutex, (TickType_t) 100) == pdTRUE) {
counter++;
xSemaphoreGive(writeMutex);
osDelay(10);
}
}
///////////////// THE UGLY GOTO PART /////////////////////////
here:
if (xSemaphoreTake(writeMutex, (TickType_t) 100) == pdTRUE) {
if (counter != 110) {
xSemaphoreGive(writeMutex);
osDelay(1);
goto here;
}
}
//////////////////////////////////////////////////////////////
snprintf((char*) buff, 100, "%d\n\r", (int) counter);
HAL_UART_Transmit(&huart2, buff, strlen((char*) buff), 1000);
}
void compassReadThread(void const * argument) {
for (uint16_t i = 0; i < 60; i++) {
if (xSemaphoreTake(writeMutex, (TickType_t) 100) == pdTRUE) {
counter++;
xSemaphoreGive(writeMutex);
osDelay(10);
}
}
}
答案 0 :(得分:2)
您可以像这样使用while循环:
while (xSemaphoreTake(writeMutex, (TickType_t) 100) == pdTRUE && counter != 110) {
xSemaphoreGive(writeMutex);
osDelay(1);
}