【问题标题】:How to replace this GOTO statement so it is clear如何替换此 GOTO 语句,以便清楚
【发布时间】:2019-03-24 09:22:42
【问题描述】:

我正在使用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);
        }
    }
}

【问题讨论】:

  • here: 替换为while(1),将goto here; 替换为break;? - 这似乎是一个简单的循环
  • 你是因为某位著名的荷兰计算机科学家的论文标题而断言这一点吗?
  • 等一下。您只是不喜欢 GOTO,因为您偶然发现了它,还是您有一个安全关键应用程序? FreeRTOS 设计师肯定有答案。您是否在整个代码库中搜索了 GOTO?结果是什么? (C 很丑)

标签: c mutex goto freertos


【解决方案1】:

你可以像这样使用一个while循环:

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

【讨论】:

  • 这是否确保它首先获取互斥体,然后检查变量计数器?
  • 是的,这叫做lazy evaluation(另见this question)。仅当第一个条件为真时才检查第二个条件。
猜你喜欢
  • 2011-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多