如何更换这个GOTO声明,这一点很清楚

问题描述 投票:0回答:1

我正在使用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);
        }
    }
}
c mutex goto freertos
1个回答
2
投票

您可以像这样使用while循环:

while (xSemaphoreTake(writeMutex, (TickType_t) 100) == pdTRUE && counter != 110) {
    xSemaphoreGive(writeMutex);
    osDelay(1);
}
© www.soinside.com 2019 - 2024. All rights reserved.