c - 如何替换此 GOTO 语句,以便清楚
问题描述
我正在使用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);
}
推荐阅读
- python - 有没有办法将 matplotlib Figure 实例组合在一起?
- java - 我们可以将 Java 中的最终重新排序规则视为发生在规则之前吗?
- c# - WeifenLuo.WinFormsUI.Docking Tab点击事件
- tensorflow - 使用 TensorFlow 1.15 和 tflearn 1.19 但此代码不起作用
- scala - 在 spark scala 中为 withcolumn 编写通用函数
- server - Cassandra 经常宕机,没有任何错误或异常
- html5-video - 对于不支持 HTML 5 的浏览器回退到 GIF 的最佳实践
- react-native - 如何在 createMaterialTopTabNavigator 上方添加组件?
- javascript - 如何在 VS Code 中将点表示法转换为括号表示法?
- veins - 我应该如何在一次模拟中使用两种车辆类型?