0

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);
        }
    }
}
g_1_k
  • 484
  • 1
  • 6
  • 13
  • replace `here: ` with `while(1)` and `goto here;` with `break;`? - this seems to be a simple loop – UnholySheep Mar 24 '19 at 09:26
  • Are you asserting this due to the title of a paper by a certain famous dutch computer scientist? – StoryTeller - Unslander Monica Mar 24 '19 at 09:26
  • Wait a sec. Do you just not like GOTO because you stumbled across it or do you have a safety critical application? FreeRTOS designers surely have an answer. Did you search the whole code base for GOTO? What’s the result? (C is ugly tbh) –  Mar 24 '19 at 09:27

1 Answers1

2

You could use a while loop like this:

while (xSemaphoreTake(writeMutex, (TickType_t) 100) == pdTRUE && counter != 110) {
    xSemaphoreGive(writeMutex);
    osDelay(1);
}
Simon Doppler
  • 1,918
  • 8
  • 26
  • Does this make sure that it takes the mutex first and after that the variable counter is checked? – g_1_k Mar 24 '19 at 09:27
  • 1
    Yes, this is called [lazy evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation) (see also [this question](https://stackoverflow.com/a/3958891/10805404)). The second condition is checked only if the first is true. – Simon Doppler Mar 24 '19 at 09:30