如何替换此 GOTO 语句使其清晰
How to replace this GOTO statement so it is clear
我正在使用 FREERTOS 和 tring 来实现互斥锁。我想知道如何重写它,这样我就不需要 GOTO(因为这是一种不好的做法),或者这是有效的 GOTO usa 案例。谢谢
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);
}
}
}
您可以像这样使用 while 循环:
while (xSemaphoreTake(writeMutex, (TickType_t) 100) == pdTRUE && counter != 110) {
xSemaphoreGive(writeMutex);
osDelay(1);
}
我正在使用 FREERTOS 和 tring 来实现互斥锁。我想知道如何重写它,这样我就不需要 GOTO(因为这是一种不好的做法),或者这是有效的 GOTO usa 案例。谢谢
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);
}
}
}
您可以像这样使用 while 循环:
while (xSemaphoreTake(writeMutex, (TickType_t) 100) == pdTRUE && counter != 110) {
xSemaphoreGive(writeMutex);
osDelay(1);
}