Skip to content

Commit 49bec8a

Browse files
Ensure mutex is created successfully, or else return an error
Check if the mutex (which ensures thread safety) was created successfully, and return an error if it wasn't. Moved this check to the top of the <<>> function, so that it doesn't need to clean up allocated memory. Since successfully creating the mutex is now a precondition for creating the list, we can safely remove the NULL checks when using the mutex.
1 parent a0d0163 commit 49bec8a

File tree

1 file changed

+9
-12
lines changed

1 file changed

+9
-12
lines changed

components/utilities/log_router/log_router.c

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -118,9 +118,7 @@ int esp_log_router_flash_vprintf(const char *format, va_list args)
118118
}
119119

120120
// Lock mutex for thread safety
121-
if (g_log_router_mutex) {
122-
xSemaphoreTake(g_log_router_mutex, portMAX_DELAY);
123-
}
121+
xSemaphoreTake(g_log_router_mutex, portMAX_DELAY);
124122

125123
// Write to all files that match the log level
126124
esp_log_router_slist_t *item;
@@ -244,9 +242,7 @@ int esp_log_router_flash_vprintf(const char *format, va_list args)
244242
}
245243

246244
// Release mutex
247-
if (g_log_router_mutex) {
248-
xSemaphoreGive(g_log_router_mutex);
249-
}
245+
xSemaphoreGive(g_log_router_mutex);
250246

251247
return ret;
252248
}
@@ -290,6 +286,13 @@ static void esp_log_router_shutdown(void)
290286

291287
esp_err_t esp_log_router_to_file(const char* file_path, const char* tag, esp_log_level_t level)
292288
{
289+
// Create mutex for thread safety
290+
g_log_router_mutex = xSemaphoreCreateMutex();
291+
if (g_log_router_mutex == NULL) {
292+
ESP_LOGW(TAG, "Failed to create mutex for log router");
293+
return ESP_ERR_NO_MEM;
294+
}
295+
293296
if (!file_path) {
294297
return ESP_ERR_INVALID_ARG;
295298
}
@@ -376,12 +379,6 @@ esp_err_t esp_log_router_to_file(const char* file_path, const char* tag, esp_log
376379
SLIST_INSERT_HEAD(&g_esp_log_router_slist_head, new_log_router, next);
377380
g_esp_log_router_vprintf = esp_log_set_vprintf(esp_log_router_flash_vprintf);
378381
esp_register_shutdown_handler(esp_log_router_shutdown);
379-
380-
// Create mutex for thread safety when first node is added
381-
g_log_router_mutex = xSemaphoreCreateMutex();
382-
if (g_log_router_mutex == NULL) {
383-
ESP_LOGW(TAG, "Failed to create mutex for log router");
384-
}
385382
} else {
386383
// Find the last node and insert after it
387384
esp_log_router_slist_t *last = SLIST_FIRST(&g_esp_log_router_slist_head);

0 commit comments

Comments
 (0)