Search code examples
cmutexgotofreertos

How to replace this GOTO statement so it is clear


I am using FREERTOS and tring to implement mutex. I would like to know how to rewrite it so I would not need GOTO(because it is a bad practise), or is this valid GOTO usa case. Thanks

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);
        }
    }
}

Solution

  • You could use a while loop like this:

    while (xSemaphoreTake(writeMutex, (TickType_t) 100) == pdTRUE && counter != 110) {
        xSemaphoreGive(writeMutex);
        osDelay(1);
    }